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.
17 use File::Temp qw(tempfile);
18 use File::Path qw(mkpath);
19 use File::Basename qw(basename dirname);
22 use POSIX qw(strftime dup2);
27 die "Need SVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
29 $SIG{'PIPE'}="IGNORE";
32 our($opt_h,$opt_o,$opt_v,$opt_u,$opt_C,$opt_i,$opt_m,$opt_M,$opt_t,$opt_T,$opt_b,$opt_r,$opt_s,$opt_l,$opt_d,$opt_D);
36 Usage: ${\basename $0} # fetch/update GIT from SVN
37 [-o branch-for-HEAD] [-h] [-v] [-l max_rev]
38 [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
39 [-d|-D] [-i] [-u] [-r] [-s start_chg] [-m] [-M regex] [SVN_URL]
44 getopts("b:C:dDhil:mM:o:rs:t:T:uv") or usage();
47 my $tag_name = $opt_t || "tags";
48 my $trunk_name = $opt_T || "trunk";
49 my $branch_name = $opt_b || "branches";
51 @ARGV == 1 or @ARGV == 2 or usage();
55 my $git_tree = $opt_C;
58 my $svn_url = $ARGV[0];
59 my $svn_dir = $ARGV[1];
63 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
66 push (@mergerx, qr/$opt_M/);
69 select(STDERR); $|=1; select(STDOUT);
73 # Basic SVN connection.
74 # We're only interested in connecting and downloading, so ...
77 use File::Temp qw(tempfile);
78 use POSIX qw(strftime dup2);
82 $what=ref($what) if ref($what);
85 $self->{'buffer'} = "";
89 $self->{'fullrep'} = $repo;
97 my $repo = $self->{'fullrep'};
98 my $auth = SVN::Core::auth_open ([SVN::Client::get_simple_provider,
99 SVN::Client::get_ssl_server_trust_file_provider,
100 SVN::Client::get_username_provider]);
101 my $s = SVN::Ra->new(url => $repo, auth => $auth);
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 my $svn2 = SVNconn->new($svn);
133 $svn = SVNconn->new($svn);
136 if($opt_d or $opt_D) {
137 $svn_url = URI->new($svn_url)->canonical;
139 $svn_dir =~ s#/*$#/#;
143 if ($svn_url->scheme eq "http") {
145 $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
147 print STDERR "Warning: not HTTP; turning off direct file access\n";
154 $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
155 or die "Unparseable date: $d\n";
156 my $y=$1; $y-=1900 if $y>1900;
157 return timegm($6||0,$5,$4,$3,$2-1,$y);
167 sub get_headref($$) {
172 if (open(C,"$git_dir/refs/heads/$name")) {
176 or die "Cannot get head id for $name ($sha): $!\n";
183 or mkdir($git_tree,0777)
184 or die "Could not create $git_tree: $!";
187 my $orig_branch = "";
188 my $forward_master = 0;
191 my $git_dir = $ENV{"GIT_DIR"} || ".git";
192 $git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
193 $ENV{"GIT_DIR"} = $git_dir;
195 $orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
196 my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
197 DIR => File::Spec->tmpdir());
199 $ENV{GIT_INDEX_FILE} = $git_index;
203 my $current_rev = $opt_s || 1;
204 unless(-d $git_dir) {
205 system("git-init-db");
206 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
207 system("git-read-tree");
208 die "Cannot init an empty tree: $?\n" if $?;
210 $last_branch = $opt_o;
213 -f "$git_dir/refs/heads/$opt_o"
214 or die "Branch '$opt_o' does not exist.\n".
215 "Either use the correct '-o branch' option,\n".
216 "or import to a new repository.\n";
218 -f "$git_dir/svn2git"
219 or die "'$git_dir/svn2git' does not exist.\n".
220 "You need that file for incremental imports.\n";
221 open(F, "git-symbolic-ref HEAD |") or
222 die "Cannot run git-symbolic-ref: $!\n";
223 chomp ($last_branch = <F>);
224 $last_branch = basename($last_branch);
226 unless($last_branch) {
227 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
228 $last_branch = "master";
230 $orig_branch = $last_branch;
231 $last_rev = get_headref($orig_branch, $git_dir);
232 if (-f "$git_dir/SVN2GIT_HEAD") {
235 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
238 git-read-tree -m -u SVN2GIT_HEAD HEAD
241 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
244 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
245 system('cmp', '-s', "$git_dir/refs/heads/master",
246 "$git_dir/refs/heads/$opt_o") == 0;
249 system('git-read-tree', $last_rev);
250 die "read-tree failed: $?\n" if $?;
252 # Get the last import timestamps
253 open my $B,"<", "$git_dir/svn2git";
256 my($num,$branch,$ref) = split;
257 $branches{$branch}{$num} = $ref;
258 $branches{$branch}{"LAST"} = $ref;
259 $current_rev = $num+1 if $current_rev <= $num;
264 or die "Could not create git subdir ($git_dir).\n";
266 open BRANCHES,">>", "$git_dir/svn2git";
269 my ($branch, $path, $revision) = @_;
270 my $pool=SVN::Pool->new;
271 my $kind = $svn->{'svn'}->check_path(revert_split_path($branch,$path),$revision,$pool);
276 sub revert_split_path($$) {
277 my($branch,$path) = @_;
280 $path = "" if $path eq "/"; # this should not happen, but ...
282 $svnpath = "$trunk_name/$path";
283 } elsif($branch =~ m#^/#) {
284 $svnpath = "$tag_name$branch/$path";
286 $svnpath = "$branch_name/$branch/$path";
294 my($rev,$branch,$path) = @_;
296 my $svnpath = revert_split_path($branch,$path);
303 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
304 my $url=$svn_url->clone();
305 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
306 print "... $path...\n" if $opt_v;
307 $req = HTTP::Request->new(GET => $url);
308 $res = $lwp_ua->request($req);
309 if ($res->is_success) {
311 ($fh, $name) = tempfile('gitsvn.XXXXXX',
312 DIR => File::Spec->tmpdir(), UNLINK => 1);
313 print $fh $res->content;
314 close($fh) or die "Could not write $name: $!\n";
316 return undef if $res->code == 301; # directory?
317 die $res->status_line." at $url\n";
320 $name = $svn->file("$svnpath",$rev);
321 return undef unless defined $name;
324 my $pid = open(my $F, '-|');
325 die $! unless defined $pid;
327 exec("git-hash-object", "-w", $name)
328 or die "Cannot create object: $!\n";
334 my $mode = "0644"; # SV does not seem to store any file modes
335 return [$mode, $sha, $path];
342 if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
344 } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
346 } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
354 print STDERR "$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
357 $path = "/" if $path eq "";
358 return ($branch,$path);
363 my ($srcbranch,$uptorev) = @_;
365 my $bbranches = $branches{$srcbranch};
366 my @revs = reverse sort { ($a eq 'LAST' ? 0 : $a) <=> ($b eq 'LAST' ? 0 : $b) } keys %$bbranches;
368 foreach my $arev(@revs) {
369 next if ($arev eq 'LAST');
370 if ($arev <= $uptorev) {
378 sub copy_path($$$$$$$$) {
379 # Somebody copied a whole subdirectory.
380 # We need to find the index entries from the old version which the
381 # SVN log entry points to, and add them to the new place.
383 my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
385 my($srcbranch,$srcpath) = split_path($rev,$oldpath);
386 unless(defined $srcbranch) {
387 print "Path not found when copying from $oldpath @ $rev\n";
390 my $therev = branch_rev($srcbranch, $rev);
391 my $gitrev = $branches{$srcbranch}{$therev};
393 print STDERR "$newrev:$newbranch: could not find $oldpath \@ $rev\n";
396 if ($srcbranch ne $newbranch) {
397 push(@$parents, $branches{$srcbranch}{'LAST'});
399 print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
400 if ($node_kind eq $SVN::Node::dir) {
401 $srcpath =~ s#/*$#/#;
404 my $pid = open my $f,'-|';
405 die $! unless defined $pid;
407 exec("git-ls-tree","-r","-z",$gitrev,$srcpath)
413 my($m,$p) = split(/\t/,$_,2);
414 my($mode,$type,$sha1) = split(/ /,$m);
415 next if $type ne "blob";
416 if ($node_kind eq $SVN::Node::dir) {
417 $p = $path . substr($p,length($srcpath)-1);
421 push(@$new,[$mode,$sha1,$p]);
424 print STDERR "$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
428 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
429 my($author_name,$author_email,$dest);
430 my(@old,@new,@parents);
432 if (not defined $author) {
433 $author_name = $author_email = "unknown";
434 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
435 ($author_name, $author_email) = ($1, $2);
437 $author =~ s/^<(.*)>$/$1/;
438 $author_name = $author_email = $author;
440 $date = pdate($date);
444 if($branch eq "/") { # trunk
446 } elsif($branch =~ m#^/(.+)#) { # tag
449 } else { # "normal" branch
455 my $prev = $changed_paths->{"/"};
456 if($prev and $prev->[0] eq "A") {
457 delete $changed_paths->{"/"};
458 my $oldpath = $prev->[1];
460 if(defined $oldpath) {
462 ($parent,$p) = split_path($revision,$oldpath);
466 $parent =~ s#^/##; # if it's a tag
474 if($revision > $opt_s and defined $parent) {
475 open(H,"git-rev-parse --verify $parent |");
478 print STDERR "$revision: cannot find commit '$parent'!\n";
482 if(length($rev) != 40) {
483 print STDERR "$revision: cannot find commit '$parent'!\n";
486 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
487 if($revision != $opt_s and not $rev) {
488 print STDERR "$revision: do not know ancestor for '$parent'!\n";
495 # if($prev and $prev->[0] eq "A") {
497 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
498 # print STDERR "$revision: Could not create branch $branch: $!\n";
503 # or die "Could not write branch $branch: $!";
505 # or die "Could not write branch $branch: $!";
508 if(not defined $rev) {
510 } elsif ($rev ne $last_rev) {
511 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
512 system("git-read-tree", $rev);
513 die "read-tree failed for $rev: $?\n" if $?;
517 push (@parents, $rev) if defined $rev;
520 if($tag and not %$changed_paths) {
523 my @paths = sort keys %$changed_paths;
524 foreach my $path(@paths) {
525 my $action = $changed_paths->{$path};
527 if ($action->[0] eq "R") {
528 # refer to a file/tree in an earlier commit
529 push(@old,$path); # remove any old stuff
531 if(($action->[0] eq "A") || ($action->[0] eq "R")) {
532 my $node_kind = node_kind($branch,$path,$revision);
534 copy_path($revision,$branch,$path,$action->[1],$action->[2],$node_kind,\@new,\@parents);
535 } elsif ($node_kind eq $SVN::Node::file) {
536 my $f = get_file($revision,$branch,$path);
540 my $opath = $action->[3];
541 print STDERR "$revision: $branch: could not fetch '$opath'\n";
544 } elsif ($action->[0] eq "D") {
546 } elsif ($action->[0] eq "M") {
547 my $node_kind = node_kind($branch,$path,$revision);
548 if ($node_kind eq $SVN::Node::file) {
549 my $f = get_file($revision,$branch,$path);
553 die "$revision: unknown action '".$action->[0]."' for $path\n";
560 @o1 = splice(@old,0,50);
565 my $pid = open my $F, "-|";
566 die "$!" unless defined $pid;
568 exec("git-ls-files", "-z", @o1) or die $!;
581 @o2 = splice(@o1,0,50);
586 system("git-update-index","--force-remove","--",@o2);
587 die "Cannot remove files: $?\n" if $?;
593 @n2 = splice(@new,0,10);
598 system("git-update-index","--add",
599 (map { ('--cacheinfo', @$_) } @n2));
600 die "Cannot add files: $?\n" if $?;
603 my $pid = open(C,"-|");
604 die "Cannot fork: $!" unless defined $pid;
606 exec("git-write-tree");
607 die "Cannot exec git-write-tree: $!\n";
609 chomp(my $tree = <C>);
611 or die "Cannot get tree id ($tree): $!\n";
613 or die "Error running git-write-tree: $?\n";
614 print "Tree ID $tree\n" if $opt_v;
616 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
617 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
619 die "Fork: $!\n" unless defined $pid;
623 open(OUT,">&STDOUT");
624 dup2($pw->fileno(),0);
625 dup2($pr->fileno(),1);
631 # loose detection of merges
632 # based on the commit msg
633 foreach my $rx (@mergerx) {
634 if ($message =~ $rx) {
636 if ($mparent eq 'HEAD') { $mparent = $opt_o };
637 if ( -e "$git_dir/refs/heads/$mparent") {
638 $mparent = get_headref($mparent, $git_dir);
639 push (@parents, $mparent);
640 print OUT "Merge parent branch: $mparent\n" if $opt_v;
644 my %seen_parents = ();
645 my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
646 foreach my $bparent (@unique_parents) {
647 push @par, '-p', $bparent;
648 print OUT "Merge parent branch: $bparent\n" if $opt_v;
652 "GIT_AUTHOR_NAME=$author_name",
653 "GIT_AUTHOR_EMAIL=$author_email",
654 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
655 "GIT_COMMITTER_NAME=$author_name",
656 "GIT_COMMITTER_EMAIL=$author_email",
657 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
658 "git-commit-tree", $tree,@par);
659 die "Cannot exec git-commit-tree: $!\n";
664 $message =~ s/[\s\n]+\z//;
665 $message = "r$revision: $message" if $opt_r;
667 print $pw "$message\n"
668 or die "Error writing to git-commit-tree: $!\n";
671 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
674 or die "Cannot get commit id ($cid): $!\n";
675 print "Commit ID $cid\n" if $opt_v;
679 die "Error running git-commit-tree: $?\n" if $?;
682 if (not defined $cid) {
683 $cid = $branches{"/"}{"LAST"};
686 if(not defined $dest) {
687 print "... no known parent\n" if $opt_v;
689 print "Writing to refs/heads/$dest\n" if $opt_v;
690 open(C,">$git_dir/refs/heads/$dest") and
691 print C ("$cid\n") and
693 or die "Cannot write branch $dest for update: $!\n";
697 my($in, $out) = ('','');
698 $last_rev = "-" if %$changed_paths;
699 # the tag was 'complex', i.e. did not refer to a "real" revision
701 $dest =~ tr/_/\./ if $opt_u;
704 my $pid = open2($in, $out, 'git-mktag');
705 print $out ("object $cid\n".
708 "tagger $author_name <$author_email>\n") and
710 or die "Cannot create tag object $dest: $!\n";
715 if ( !close($in) or waitpid($pid, 0) != $pid or
716 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
717 die "Cannot create tag object $dest: $!\n";
720 open(C,">$git_dir/refs/tags/$dest") and
721 print C ("$tagobj\n") and
723 or die "Cannot create tag $branch: $!\n";
725 print "Created tag '$dest' on '$branch'\n" if $opt_v;
727 $branches{$branch}{"LAST"} = $cid;
728 $branches{$branch}{$revision} = $cid;
730 print BRANCHES "$revision $branch $cid\n";
731 print "DONE: $revision $dest $cid\n" if $opt_v;
735 # Recursive use of the SVN connection does not work
738 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
740 while(my($path,$action) = each %$changed_paths) {
741 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
743 $changed_paths = \%p;
750 while(my($path,$action) = each %$changed_paths) {
751 ($branch,$path) = split_path($revision,$path);
752 next if not defined $branch;
753 $done{$branch}{$path} = $action;
755 while(($branch,$changed_paths) = each %done) {
756 commit($branch, $changed_paths, $revision, $author, $date, $message);
760 $opt_l = $svn->{'maxrev'} if not defined $opt_l or $opt_l > $svn->{'maxrev'};
762 if ($svn->{'maxrev'} < $current_rev) {
763 print "Up to date: no new revisions to fetch!\n" if $opt_v;
764 unlink("$git_dir/SVN2GIT_HEAD");
768 print "Fetching from $current_rev to $opt_l ...\n" if $opt_v;
770 my $pool=SVN::Pool->new;
771 $svn->{'svn'}->get_log("/",$current_rev,$opt_l,0,1,1,\&commit_all,$pool);
777 if (defined $orig_git_index) {
778 $ENV{GIT_INDEX_FILE} = $orig_git_index;
780 delete $ENV{GIT_INDEX_FILE};
783 # Now switch back to the branch we were in before all of this happened
785 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
786 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
789 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
790 die "read-tree failed: $?\n" if $?;
793 $orig_branch = "master";
794 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
795 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
796 unless -f "$git_dir/refs/heads/master";
797 system('git-update-ref', 'HEAD', "$orig_branch");
799 system('git checkout');
800 die "checkout failed: $?\n" if $?;
803 unlink("$git_dir/SVN2GIT_HEAD");