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 SVN connection.
10 # The head revision is on branch "origin" by default.
11 # You can change that with the '-o' option.
13 require 5.008; # for shell-safe open("-|",LIST)
18 use File::Temp qw(tempfile);
19 use File::Path qw(mkpath);
20 use File::Basename qw(basename dirname);
23 use POSIX qw(strftime dup2);
28 die "Need CVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
30 $SIG{'PIPE'}="IGNORE";
33 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,$opt_d,$opt_D);
37 Usage: ${\basename $0} # fetch/update GIT from CVS
38 [-o branch-for-HEAD] [-h] [-v] [-l max_num_changes]
39 [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
40 [-d|-D] [-i] [-u] [-s start_chg] [-m] [-M regex] [SVN_URL]
45 getopts("b:C:dDhil:mM:o:s:t:T:uv") or usage();
48 my $tag_name = $opt_t || "tags";
49 my $trunk_name = $opt_T || "trunk";
50 my $branch_name = $opt_b || "branches";
52 @ARGV == 1 or @ARGV == 2 or usage();
56 $opt_l = 100 unless defined $opt_l;
57 my $git_tree = $opt_C;
60 my $svn_url = $ARGV[0];
61 my $svn_dir = $ARGV[1];
65 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
68 push (@mergerx, qr/$opt_M/);
71 select(STDERR); $|=1; select(STDOUT);
75 # Basic SVN connection.
76 # We're only interested in connecting and downloading, so ...
79 use File::Temp qw(tempfile);
80 use POSIX qw(strftime dup2);
84 $what=ref($what) if ref($what);
87 $self->{'buffer'} = "";
91 $self->{'fullrep'} = $repo;
99 my $repo = $self->{'fullrep'};
100 my $s = SVN::Ra->new($repo);
102 die "SVN connection to $repo: $!\n" unless defined $s;
104 $self->{'repo'} = $repo;
105 $self->{'maxrev'} = $s->get_latest_revnum();
109 my($self,$path,$rev) = @_;
111 my ($fh, $name) = tempfile('gitsvn.XXXXXX',
112 DIR => File::Spec->tmpdir(), UNLINK => 1);
114 print "... $rev $path ...\n" if $opt_v;
115 my $pool = SVN::Pool->new();
116 eval { $self->{'svn'}->get_file($path,$rev,$fh,$pool); };
119 return undef if $@ =~ /Attempted to get checksum/;
131 $svn .= "/$svn_dir" if defined $svn_dir;
132 $svn = SVNconn->new($svn);
135 if($opt_d or $opt_D) {
136 $svn_url = URI->new($svn_url)->canonical;
138 $svn_dir =~ s#/*$#/#;
142 if ($svn_url->scheme eq "http") {
144 $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
146 print STDERR "Warning: not HTTP; turning off direct file access\n";
153 $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
154 or die "Unparseable date: $d\n";
155 my $y=$1; $y-=1900 if $y>1900;
156 return timegm($6||0,$5,$4,$3,$2-1,$y);
166 sub get_headref($$) {
171 if (open(C,"$git_dir/refs/heads/$name")) {
175 or die "Cannot get head id for $name ($sha): $!\n";
182 or mkdir($git_tree,0777)
183 or die "Could not create $git_tree: $!";
186 my $orig_branch = "";
187 my $forward_master = 0;
190 my $git_dir = $ENV{"GIT_DIR"} || ".git";
191 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
192 $ENV{"GIT_DIR"} = $git_dir;
194 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
195 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
196 DIR => File::Spec->tmpdir());
198 $ENV{GIT_INDEX_FILE} = $git_index;
202 my $current_rev = $opt_s-1;
203 unless(-d $git_dir) {
204 system("git-init-db");
205 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
206 system("git-read-tree");
207 die "Cannot init an empty tree: $?\n" if $?;
209 $last_branch = $opt_o;
212 -f "$git_dir/refs/heads/$opt_o"
213 or die "Branch '$opt_o' does not exist.\n".
214 "Either use the correct '-o branch' option,\n".
215 "or import to a new repository.\n";
217 -f "$git_dir/svn2git"
218 or die "'$git_dir/svn2git' does not exist.\n".
219 "You need that file for incremental imports.\n";
220 $last_branch = basename(readlink("$git_dir/HEAD"));
221 unless($last_branch) {
222 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
223 $last_branch = "master";
225 $orig_branch = $last_branch;
226 $last_rev = get_headref($orig_branch, $git_dir);
227 if (-f "$git_dir/SVN2GIT_HEAD") {
230 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
233 git-read-tree -m -u SVN2GIT_HEAD HEAD
236 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
239 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
240 system('cmp', '-s', "$git_dir/refs/heads/master",
241 "$git_dir/refs/heads/$opt_o") == 0;
244 system('git-read-tree', $last_rev);
245 die "read-tree failed: $?\n" if $?;
247 # Get the last import timestamps
248 open my $B,"<", "$git_dir/svn2git";
251 my($num,$branch,$ref) = split;
252 $branches{$branch}{$num} = $ref;
253 $branches{$branch}{"LAST"} = $ref;
254 $current_rev = $num if $current_rev < $num;
259 or die "Could not create git subdir ($git_dir).\n";
261 open BRANCHES,">>", "$git_dir/svn2git";
264 my($rev,$branch,$path) = @_;
266 # revert split_path(), below
268 $path = "" if $path eq "/"; # this should not happen, but ...
270 $svnpath = "$trunk_name/$path";
271 } elsif($branch =~ m#^/#) {
272 $svnpath = "$tag_name$branch/$path";
274 $svnpath = "$branch_name/$branch/$path";
282 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
283 my $url=$svn_url->clone();
284 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
285 print "... $path...\n" if $opt_v;
286 $req = HTTP::Request->new(GET => $url);
287 $res = $lwp_ua->request($req);
288 if ($res->is_success) {
290 ($fh, $name) = tempfile('gitsvn.XXXXXX',
291 DIR => File::Spec->tmpdir(), UNLINK => 1);
292 print $fh $res->content;
293 close($fh) or die "Could not write $name: $!\n";
295 return undef if $res->code == 301; # directory?
296 die $res->status_line." at $url\n";
299 $name = $svn->file("/$svnpath",$rev);
300 return undef unless defined $name;
303 open my $F, '-|', "git-hash-object", "-w", $name
304 or die "Cannot create object: $!\n";
309 my $mode = "0644"; # SV does not seem to store any file modes
310 return [$mode, $sha, $path];
317 if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
319 } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
321 } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
324 print STDERR "$rev: Unrecognized path: $path\n";
327 $path = "/" if $path eq "";
328 return ($branch,$path);
331 sub copy_subdir($$$$$$) {
332 # Somebody copied a whole subdirectory.
333 # We need to find the index entries from the old version which the
334 # SVN log entry points to, and add them to the new place.
336 my($newrev,$newbranch,$path,$oldpath,$rev,$new) = @_;
337 my($branch,$srcpath) = split_path($rev,$oldpath);
339 my $gitrev = $branches{$branch}{$rev};
341 print STDERR "$newrev:$newbranch: could not find $oldpath \@ $rev\n";
344 print "$newrev:$newbranch:$path: copying from $branch:$srcpath @ $rev\n" if $opt_v;
345 $srcpath =~ s#/*$#/#;
346 open my $f,"-|","git-ls-tree","-r","-z",$gitrev,$srcpath;
350 my($m,$p) = split(/\t/,$_,2);
351 my($mode,$type,$sha1) = split(/ /,$m);
352 next if $type ne "blob";
353 $p = substr($p,length($srcpath)-1);
354 print "... found $path$p ...\n" if $opt_v;
355 push(@$new,[$mode,$sha1,$path.$p]);
358 print STDERR "$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
362 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
363 my($author_name,$author_email,$dest);
366 if (not defined $author) {
367 $author_name = $author_email = "unknown";
368 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
369 ($author_name, $author_email) = ($1, $2);
371 $author =~ s/^<(.*)>$/$1/;
372 $author_name = $author_email = $author;
374 $date = pdate($date);
378 if($branch eq "/") { # trunk
380 } elsif($branch =~ m#^/(.+)#) { # tag
383 } else { # "normal" branch
389 my $prev = $changed_paths->{"/"};
390 if($prev and $prev->[0] eq "A") {
391 delete $changed_paths->{"/"};
392 my $oldpath = $prev->[1];
394 if(defined $oldpath) {
396 ($parent,$p) = split_path($revision,$oldpath);
400 $parent =~ s#^/##; # if it's a tag
408 if($revision > $opt_s and defined $parent) {
409 open(H,"git-rev-parse --verify $parent |");
412 print STDERR "$revision: cannot find commit '$parent'!\n";
416 if(length($rev) != 40) {
417 print STDERR "$revision: cannot find commit '$parent'!\n";
420 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
421 if($revision != $opt_s and not $rev) {
422 print STDERR "$revision: do not know ancestor for '$parent'!\n";
429 # if($prev and $prev->[0] eq "A") {
431 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
432 # print STDERR "$revision: Could not create branch $branch: $!\n";
437 # or die "Could not write branch $branch: $!";
439 # or die "Could not write branch $branch: $!";
442 if(not defined $rev) {
444 } elsif ($rev ne $last_rev) {
445 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
446 system("git-read-tree", $rev);
447 die "read-tree failed for $rev: $?\n" if $?;
452 if($tag and not %$changed_paths) {
455 my @paths = sort keys %$changed_paths;
456 foreach my $path(@paths) {
457 my $action = $changed_paths->{$path};
459 if ($action->[0] eq "A") {
460 my $f = get_file($revision,$branch,$path);
463 } elsif($action->[1]) {
464 copy_subdir($revision,$branch,$path,$action->[1],$action->[2],\@new);
466 my $opath = $action->[3];
467 print STDERR "$revision: $branch: could not fetch '$opath'\n";
469 } elsif ($action->[0] eq "D") {
471 } elsif ($action->[0] eq "M") {
472 my $f = get_file($revision,$branch,$path);
474 } elsif ($action->[0] eq "R") {
475 # refer to a file/tree in an earlier commit
476 push(@old,$path); # remove any old stuff
478 # ... and add any new stuff
479 my($b,$srcpath) = split_path($revision,$action->[1]);
480 $srcpath =~ s#/*$#/#;
481 open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $srcpath;
485 my($m,$p) = split(/\t/,$_,2);
486 my($mode,$type,$sha1) = split(/ /,$m);
487 next if $type ne "blob";
488 $p = substr($p,length($srcpath)-1);
489 push(@new,[$mode,$sha1,$path.$p]);
493 die "$revision: unknown action '".$action->[0]."' for $path\n";
498 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
510 @o2 = splice(@old,0,50);
515 system("git-update-index","--force-remove","--",@o2);
516 die "Cannot remove files: $?\n" if $?;
522 @n2 = splice(@new,0,10);
527 system("git-update-index","--add",
528 (map { ('--cacheinfo', @$_) } @n2));
529 die "Cannot add files: $?\n" if $?;
532 my $pid = open(C,"-|");
533 die "Cannot fork: $!" unless defined $pid;
535 exec("git-write-tree");
536 die "Cannot exec git-write-tree: $!\n";
538 chomp(my $tree = <C>);
540 or die "Cannot get tree id ($tree): $!\n";
542 or die "Error running git-write-tree: $?\n";
543 print "Tree ID $tree\n" if $opt_v;
545 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
546 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
548 die "Fork: $!\n" unless defined $pid;
552 open(OUT,">&STDOUT");
553 dup2($pw->fileno(),0);
554 dup2($pr->fileno(),1);
559 @par = ("-p",$rev) if defined $rev;
561 # loose detection of merges
562 # based on the commit msg
563 foreach my $rx (@mergerx) {
564 if ($message =~ $rx) {
566 if ($mparent eq 'HEAD') { $mparent = $opt_o };
567 if ( -e "$git_dir/refs/heads/$mparent") {
568 $mparent = get_headref($mparent, $git_dir);
569 push @par, '-p', $mparent;
570 print OUT "Merge parent branch: $mparent\n" if $opt_v;
576 "GIT_AUTHOR_NAME=$author_name",
577 "GIT_AUTHOR_EMAIL=$author_email",
578 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
579 "GIT_COMMITTER_NAME=$author_name",
580 "GIT_COMMITTER_EMAIL=$author_email",
581 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
582 "git-commit-tree", $tree,@par);
583 die "Cannot exec git-commit-tree: $!\n";
588 $message =~ s/[\s\n]+\z//;
590 print $pw "$message\n"
591 or die "Error writing to git-commit-tree: $!\n";
594 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
597 or die "Cannot get commit id ($cid): $!\n";
598 print "Commit ID $cid\n" if $opt_v;
602 die "Error running git-commit-tree: $?\n" if $?;
605 if(not defined $dest) {
606 print "... no known parent\n" if $opt_v;
608 print "Writing to refs/heads/$dest\n" if $opt_v;
609 open(C,">$git_dir/refs/heads/$dest") and
610 print C ("$cid\n") and
612 or die "Cannot write branch $dest for update: $!\n";
616 my($in, $out) = ('','');
617 $last_rev = "-" if %$changed_paths;
618 # the tag was 'complex', i.e. did not refer to a "real" revision
620 $dest =~ tr/_/\./ if $opt_u;
622 my $pid = open2($in, $out, 'git-mktag');
623 print $out ("object $cid\n".
626 "tagger $author_name <$author_email>\n") and
628 or die "Cannot create tag object $dest: $!\n";
633 if ( !close($in) or waitpid($pid, 0) != $pid or
634 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
635 die "Cannot create tag object $dest: $!\n";
638 open(C,">$git_dir/refs/tags/$dest") and
639 print C ("$tagobj\n") and
641 or die "Cannot create tag $branch: $!\n";
643 print "Created tag '$dest' on '$branch'\n" if $opt_v;
645 $branches{$branch}{"LAST"} = $cid;
646 $branches{$branch}{$revision} = $cid;
648 print BRANCHES "$revision $branch $cid\n";
649 print "DONE: $revision $dest $cid\n" if $opt_v;
652 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
654 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
656 while(my($path,$action) = each %$changed_paths) {
657 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
659 $changed_paths = \%p;
668 while(my($path,$action) = each %$changed_paths) {
669 ($branch,$path) = split_path($revision,$path);
670 next if not defined $branch;
671 $done{$branch}{$path} = $action;
673 while(($branch,$changed_paths) = each %done) {
674 commit($branch, $changed_paths, $revision, $author, $date, $message);
678 while(++$current_rev <= $svn->{'maxrev'}) {
679 my $pool=SVN::Pool->new;
680 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,1,1,1,\&_commit_all,$pool);
683 if($opt_l and not --$opt_l) {
684 print STDERR "Stopping, because there is a memory leak (in the SVN library).\n";
685 print STDERR "Please repeat this command; it will continue safely\n";
693 if (defined $orig_git_index) {
694 $ENV{GIT_INDEX_FILE} = $orig_git_index;
696 delete $ENV{GIT_INDEX_FILE};
699 # Now switch back to the branch we were in before all of this happened
701 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
702 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
705 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
706 die "read-tree failed: $?\n" if $?;
709 $orig_branch = "master";
710 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
711 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
712 unless -f "$git_dir/refs/heads/master";
713 unlink("$git_dir/HEAD");
714 symlink("refs/heads/$orig_branch","$git_dir/HEAD");
716 system('git checkout');
717 die "checkout failed: $?\n" if $?;
720 unlink("$git_dir/SVN2GIT_HEAD");