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 SVN: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 SVN
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 my $git_tree = $opt_C;
59 my $svn_url = $ARGV[0];
60 my $svn_dir = $ARGV[1];
64 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
67 push (@mergerx, qr/$opt_M/);
70 select(STDERR); $|=1; select(STDOUT);
74 # Basic SVN connection.
75 # We're only interested in connecting and downloading, so ...
78 use File::Temp qw(tempfile);
79 use POSIX qw(strftime dup2);
83 $what=ref($what) if ref($what);
86 $self->{'buffer'} = "";
90 $self->{'fullrep'} = $repo;
98 my $repo = $self->{'fullrep'};
99 my $s = SVN::Ra->new($repo);
101 die "SVN connection to $repo: $!\n" unless defined $s;
103 $self->{'repo'} = $repo;
104 $self->{'maxrev'} = $s->get_latest_revnum();
108 my($self,$path,$rev) = @_;
110 my ($fh, $name) = tempfile('gitsvn.XXXXXX',
111 DIR => File::Spec->tmpdir(), UNLINK => 1);
113 print "... $rev $path ...\n" if $opt_v;
114 my $pool = SVN::Pool->new();
115 eval { $self->{'svn'}->get_file($path,$rev,$fh,$pool); };
118 return undef if $@ =~ /Attempted to get checksum/;
130 $svn .= "/$svn_dir" if defined $svn_dir;
131 $svn = SVNconn->new($svn);
134 if($opt_d or $opt_D) {
135 $svn_url = URI->new($svn_url)->canonical;
137 $svn_dir =~ s#/*$#/#;
141 if ($svn_url->scheme eq "http") {
143 $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
145 print STDERR "Warning: not HTTP; turning off direct file access\n";
152 $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
153 or die "Unparseable date: $d\n";
154 my $y=$1; $y-=1900 if $y>1900;
155 return timegm($6||0,$5,$4,$3,$2-1,$y);
165 sub get_headref($$) {
170 if (open(C,"$git_dir/refs/heads/$name")) {
174 or die "Cannot get head id for $name ($sha): $!\n";
181 or mkdir($git_tree,0777)
182 or die "Could not create $git_tree: $!";
185 my $orig_branch = "";
186 my $forward_master = 0;
189 my $git_dir = $ENV{"GIT_DIR"} || ".git";
190 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
191 $ENV{"GIT_DIR"} = $git_dir;
193 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
194 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
195 DIR => File::Spec->tmpdir());
197 $ENV{GIT_INDEX_FILE} = $git_index;
201 my $current_rev = $opt_s-1;
202 unless(-d $git_dir) {
203 system("git-init-db");
204 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
205 system("git-read-tree");
206 die "Cannot init an empty tree: $?\n" if $?;
208 $last_branch = $opt_o;
211 -f "$git_dir/refs/heads/$opt_o"
212 or die "Branch '$opt_o' does not exist.\n".
213 "Either use the correct '-o branch' option,\n".
214 "or import to a new repository.\n";
216 -f "$git_dir/svn2git"
217 or die "'$git_dir/svn2git' does not exist.\n".
218 "You need that file for incremental imports.\n";
219 open(F, "git-symbolic-ref HEAD |") or
220 die "Cannot run git-symbolic-ref: $!\n";
221 chomp ($last_branch = <F>);
222 $last_branch = basename($last_branch);
224 unless($last_branch) {
225 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
226 $last_branch = "master";
228 $orig_branch = $last_branch;
229 $last_rev = get_headref($orig_branch, $git_dir);
230 if (-f "$git_dir/SVN2GIT_HEAD") {
233 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
236 git-read-tree -m -u SVN2GIT_HEAD HEAD
239 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
242 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
243 system('cmp', '-s', "$git_dir/refs/heads/master",
244 "$git_dir/refs/heads/$opt_o") == 0;
247 system('git-read-tree', $last_rev);
248 die "read-tree failed: $?\n" if $?;
250 # Get the last import timestamps
251 open my $B,"<", "$git_dir/svn2git";
254 my($num,$branch,$ref) = split;
255 $branches{$branch}{$num} = $ref;
256 $branches{$branch}{"LAST"} = $ref;
257 $current_rev = $num if $current_rev < $num;
262 or die "Could not create git subdir ($git_dir).\n";
264 open BRANCHES,">>", "$git_dir/svn2git";
267 my ($branch, $path, $revision) = @_;
268 my $pool=SVN::Pool->new;
269 my $kind = $svn->{'svn'}->check_path(revert_split_path($branch,$path),$revision,$pool);
274 sub revert_split_path($$) {
275 my($branch,$path) = @_;
278 $path = "" if $path eq "/"; # this should not happen, but ...
280 $svnpath = "$trunk_name/$path";
281 } elsif($branch =~ m#^/#) {
282 $svnpath = "$tag_name$branch/$path";
284 $svnpath = "$branch_name/$branch/$path";
292 my($rev,$branch,$path) = @_;
294 my $svnpath = revert_split_path($branch,$path);
301 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
302 my $url=$svn_url->clone();
303 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
304 print "... $path...\n" if $opt_v;
305 $req = HTTP::Request->new(GET => $url);
306 $res = $lwp_ua->request($req);
307 if ($res->is_success) {
309 ($fh, $name) = tempfile('gitsvn.XXXXXX',
310 DIR => File::Spec->tmpdir(), UNLINK => 1);
311 print $fh $res->content;
312 close($fh) or die "Could not write $name: $!\n";
314 return undef if $res->code == 301; # directory?
315 die $res->status_line." at $url\n";
318 $name = $svn->file("/$svnpath",$rev);
319 return undef unless defined $name;
322 open my $F, '-|', "git-hash-object", "-w", $name
323 or die "Cannot create object: $!\n";
328 my $mode = "0644"; # SV does not seem to store any file modes
329 return [$mode, $sha, $path];
336 if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
338 } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
340 } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
348 print STDERR "$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
351 $path = "/" if $path eq "";
352 return ($branch,$path);
357 my ($srcbranch,$uptorev) = @_;
359 my $bbranches = $branches{$srcbranch};
360 my @revs = reverse sort { ($a eq 'LAST' ? 0 : $a) <=> ($b eq 'LAST' ? 0 : $b) } keys %$bbranches;
362 foreach my $arev(@revs) {
363 next if ($arev eq 'LAST');
364 if ($arev <= $uptorev) {
372 sub copy_path($$$$$$$$) {
373 # Somebody copied a whole subdirectory.
374 # We need to find the index entries from the old version which the
375 # SVN log entry points to, and add them to the new place.
377 my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
379 my($srcbranch,$srcpath) = split_path($rev,$oldpath);
380 unless(defined $srcbranch) {
381 print "Path not found when copying from $oldpath @ $rev\n";
384 my $therev = branch_rev($srcbranch, $rev);
385 my $gitrev = $branches{$srcbranch}{$therev};
387 print STDERR "$newrev:$newbranch: could not find $oldpath \@ $rev\n";
390 if ($srcbranch ne $newbranch) {
391 push(@$parents, $branches{$srcbranch}{'LAST'});
393 print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
394 if ($node_kind eq $SVN::Node::dir) {
395 $srcpath =~ s#/*$#/#;
398 open my $f,"-|","git-ls-tree","-r","-z",$gitrev,$srcpath;
402 my($m,$p) = split(/\t/,$_,2);
403 my($mode,$type,$sha1) = split(/ /,$m);
404 next if $type ne "blob";
405 if ($node_kind eq $SVN::Node::dir) {
406 $p = $path . substr($p,length($srcpath)-1);
410 push(@$new,[$mode,$sha1,$p]);
413 print STDERR "$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
417 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
418 my($author_name,$author_email,$dest);
419 my(@old,@new,@parents);
421 if (not defined $author) {
422 $author_name = $author_email = "unknown";
423 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
424 ($author_name, $author_email) = ($1, $2);
426 $author =~ s/^<(.*)>$/$1/;
427 $author_name = $author_email = $author;
429 $date = pdate($date);
433 if($branch eq "/") { # trunk
435 } elsif($branch =~ m#^/(.+)#) { # tag
438 } else { # "normal" branch
444 my $prev = $changed_paths->{"/"};
445 if($prev and $prev->[0] eq "A") {
446 delete $changed_paths->{"/"};
447 my $oldpath = $prev->[1];
449 if(defined $oldpath) {
451 ($parent,$p) = split_path($revision,$oldpath);
455 $parent =~ s#^/##; # if it's a tag
463 if($revision > $opt_s and defined $parent) {
464 open(H,"git-rev-parse --verify $parent |");
467 print STDERR "$revision: cannot find commit '$parent'!\n";
471 if(length($rev) != 40) {
472 print STDERR "$revision: cannot find commit '$parent'!\n";
475 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
476 if($revision != $opt_s and not $rev) {
477 print STDERR "$revision: do not know ancestor for '$parent'!\n";
484 # if($prev and $prev->[0] eq "A") {
486 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
487 # print STDERR "$revision: Could not create branch $branch: $!\n";
492 # or die "Could not write branch $branch: $!";
494 # or die "Could not write branch $branch: $!";
497 if(not defined $rev) {
499 } elsif ($rev ne $last_rev) {
500 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
501 system("git-read-tree", $rev);
502 die "read-tree failed for $rev: $?\n" if $?;
506 push (@parents, $rev) if defined $rev;
509 if($tag and not %$changed_paths) {
512 my @paths = sort keys %$changed_paths;
513 foreach my $path(@paths) {
514 my $action = $changed_paths->{$path};
516 if ($action->[0] eq "R") {
517 # refer to a file/tree in an earlier commit
518 push(@old,$path); # remove any old stuff
520 if(($action->[0] eq "A") || ($action->[0] eq "R")) {
521 my $node_kind = node_kind($branch,$path,$revision);
523 copy_path($revision,$branch,$path,$action->[1],$action->[2],$node_kind,\@new,\@parents);
524 } elsif ($node_kind eq $SVN::Node::file) {
525 my $f = get_file($revision,$branch,$path);
529 my $opath = $action->[3];
530 print STDERR "$revision: $branch: could not fetch '$opath'\n";
533 } elsif ($action->[0] eq "D") {
535 } elsif ($action->[0] eq "M") {
536 my $node_kind = node_kind($branch,$path,$revision);
537 if ($node_kind eq $SVN::Node::file) {
538 my $f = get_file($revision,$branch,$path);
542 die "$revision: unknown action '".$action->[0]."' for $path\n";
547 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
559 @o2 = splice(@old,0,50);
564 system("git-update-index","--force-remove","--",@o2);
565 die "Cannot remove files: $?\n" if $?;
571 @n2 = splice(@new,0,10);
576 system("git-update-index","--add",
577 (map { ('--cacheinfo', @$_) } @n2));
578 die "Cannot add files: $?\n" if $?;
581 my $pid = open(C,"-|");
582 die "Cannot fork: $!" unless defined $pid;
584 exec("git-write-tree");
585 die "Cannot exec git-write-tree: $!\n";
587 chomp(my $tree = <C>);
589 or die "Cannot get tree id ($tree): $!\n";
591 or die "Error running git-write-tree: $?\n";
592 print "Tree ID $tree\n" if $opt_v;
594 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
595 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
597 die "Fork: $!\n" unless defined $pid;
601 open(OUT,">&STDOUT");
602 dup2($pw->fileno(),0);
603 dup2($pr->fileno(),1);
609 # loose detection of merges
610 # based on the commit msg
611 foreach my $rx (@mergerx) {
612 if ($message =~ $rx) {
614 if ($mparent eq 'HEAD') { $mparent = $opt_o };
615 if ( -e "$git_dir/refs/heads/$mparent") {
616 $mparent = get_headref($mparent, $git_dir);
617 push (@parents, $mparent);
618 print OUT "Merge parent branch: $mparent\n" if $opt_v;
622 my %seen_parents = ();
623 my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
624 foreach my $bparent (@unique_parents) {
625 push @par, '-p', $bparent;
626 print OUT "Merge parent branch: $bparent\n" if $opt_v;
630 "GIT_AUTHOR_NAME=$author_name",
631 "GIT_AUTHOR_EMAIL=$author_email",
632 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
633 "GIT_COMMITTER_NAME=$author_name",
634 "GIT_COMMITTER_EMAIL=$author_email",
635 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
636 "git-commit-tree", $tree,@par);
637 die "Cannot exec git-commit-tree: $!\n";
642 $message =~ s/[\s\n]+\z//;
644 print $pw "$message\n"
645 or die "Error writing to git-commit-tree: $!\n";
648 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
651 or die "Cannot get commit id ($cid): $!\n";
652 print "Commit ID $cid\n" if $opt_v;
656 die "Error running git-commit-tree: $?\n" if $?;
659 if (not defined $cid) {
660 $cid = $branches{"/"}{"LAST"};
663 if(not defined $dest) {
664 print "... no known parent\n" if $opt_v;
666 print "Writing to refs/heads/$dest\n" if $opt_v;
667 open(C,">$git_dir/refs/heads/$dest") and
668 print C ("$cid\n") and
670 or die "Cannot write branch $dest for update: $!\n";
674 my($in, $out) = ('','');
675 $last_rev = "-" if %$changed_paths;
676 # the tag was 'complex', i.e. did not refer to a "real" revision
678 $dest =~ tr/_/\./ if $opt_u;
681 my $pid = open2($in, $out, 'git-mktag');
682 print $out ("object $cid\n".
685 "tagger $author_name <$author_email>\n") and
687 or die "Cannot create tag object $dest: $!\n";
692 if ( !close($in) or waitpid($pid, 0) != $pid or
693 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
694 die "Cannot create tag object $dest: $!\n";
697 open(C,">$git_dir/refs/tags/$dest") and
698 print C ("$tagobj\n") and
700 or die "Cannot create tag $branch: $!\n";
702 print "Created tag '$dest' on '$branch'\n" if $opt_v;
704 $branches{$branch}{"LAST"} = $cid;
705 $branches{$branch}{$revision} = $cid;
707 print BRANCHES "$revision $branch $cid\n";
708 print "DONE: $revision $dest $cid\n" if $opt_v;
711 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
713 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
715 while(my($path,$action) = each %$changed_paths) {
716 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
718 $changed_paths = \%p;
727 while(my($path,$action) = each %$changed_paths) {
728 ($branch,$path) = split_path($revision,$path);
729 next if not defined $branch;
730 $done{$branch}{$path} = $action;
732 while(($branch,$changed_paths) = each %done) {
733 commit($branch, $changed_paths, $revision, $author, $date, $message);
737 while(++$current_rev <= $svn->{'maxrev'}) {
738 if (defined $opt_l) {
744 my $pool=SVN::Pool->new;
745 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,1,1,1,\&_commit_all,$pool);
753 if (defined $orig_git_index) {
754 $ENV{GIT_INDEX_FILE} = $orig_git_index;
756 delete $ENV{GIT_INDEX_FILE};
759 # Now switch back to the branch we were in before all of this happened
761 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
762 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
765 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
766 die "read-tree failed: $?\n" if $?;
769 $orig_branch = "master";
770 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
771 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
772 unless -f "$git_dir/refs/heads/master";
773 system('git-update-ref', 'HEAD', "$orig_branch");
775 system('git checkout');
776 die "checkout failed: $?\n" if $?;
779 unlink("$git_dir/SVN2GIT_HEAD");