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 $last_branch = basename
(readlink("$git_dir/HEAD"));
220 unless($last_branch) {
221 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
222 $last_branch = "master";
224 $orig_branch = $last_branch;
225 $last_rev = get_headref
($orig_branch, $git_dir);
226 if (-f
"$git_dir/SVN2GIT_HEAD") {
229 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
232 git-read-tree -m -u SVN2GIT_HEAD HEAD
235 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
238 $opt_o ne 'master' && -f
"$git_dir/refs/heads/master" &&
239 system('cmp', '-s', "$git_dir/refs/heads/master",
240 "$git_dir/refs/heads/$opt_o") == 0;
243 system('git-read-tree', $last_rev);
244 die "read-tree failed: $?\n" if $?
;
246 # Get the last import timestamps
247 open my $B,"<", "$git_dir/svn2git";
250 my($num,$branch,$ref) = split;
251 $branches{$branch}{$num} = $ref;
252 $branches{$branch}{"LAST"} = $ref;
253 $current_rev = $num if $current_rev < $num;
258 or die "Could not create git subdir ($git_dir).\n";
260 open BRANCHES
,">>", "$git_dir/svn2git";
263 my ($branch, $path, $revision) = @_;
264 my $pool=SVN
::Pool
->new;
265 my $kind = $svn->{'svn'}->check_path(revert_split_path
($branch,$path),$revision,$pool);
270 sub revert_split_path
($$) {
271 my($branch,$path) = @_;
274 $path = "" if $path eq "/"; # this should not happen, but ...
276 $svnpath = "$trunk_name/$path";
277 } elsif($branch =~ m
#^/#) {
278 $svnpath = "$tag_name$branch/$path";
280 $svnpath = "$branch_name/$branch/$path";
288 my($rev,$branch,$path) = @_;
290 my $svnpath = revert_split_path
($branch,$path);
297 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
298 my $url=$svn_url->clone();
299 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
300 print "... $path...\n" if $opt_v;
301 $req = HTTP
::Request
->new(GET
=> $url);
302 $res = $lwp_ua->request($req);
303 if ($res->is_success) {
305 ($fh, $name) = tempfile
('gitsvn.XXXXXX',
306 DIR
=> File
::Spec
->tmpdir(), UNLINK
=> 1);
307 print $fh $res->content;
308 close($fh) or die "Could not write $name: $!\n";
310 return undef if $res->code == 301; # directory?
311 die $res->status_line." at $url\n";
314 $name = $svn->file("/$svnpath",$rev);
315 return undef unless defined $name;
318 open my $F, '-|', "git-hash-object", "-w", $name
319 or die "Cannot create object: $!\n";
324 my $mode = "0644"; # SV does not seem to store any file modes
325 return [$mode, $sha, $path];
332 if($path =~ s
#^/\Q$tag_name\E/([^/]+)/?##) {
334 } elsif($path =~ s
#^/\Q$trunk_name\E/?##) {
336 } elsif($path =~ s
#^/\Q$branch_name\E/([^/]+)/?##) {
344 print STDERR
"$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
347 $path = "/" if $path eq "";
348 return ($branch,$path);
353 my ($srcbranch,$uptorev) = @_;
355 my $bbranches = $branches{$srcbranch};
356 my @revs = reverse sort { ($a eq 'LAST' ?
0 : $a) <=> ($b eq 'LAST' ?
0 : $b) } keys %$bbranches;
358 foreach my $arev(@revs) {
359 next if ($arev eq 'LAST');
360 if ($arev <= $uptorev) {
368 sub copy_path
($$$$$$$$) {
369 # Somebody copied a whole subdirectory.
370 # We need to find the index entries from the old version which the
371 # SVN log entry points to, and add them to the new place.
373 my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
375 my($srcbranch,$srcpath) = split_path
($rev,$oldpath);
376 unless(defined $srcbranch) {
377 print "Path not found when copying from $oldpath @ $rev\n";
380 my $therev = branch_rev
($srcbranch, $rev);
381 my $gitrev = $branches{$srcbranch}{$therev};
383 print STDERR
"$newrev:$newbranch: could not find $oldpath \@ $rev\n";
386 if ($srcbranch ne $newbranch) {
387 push(@
$parents, $branches{$srcbranch}{'LAST'});
389 print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
390 if ($node_kind eq $SVN::Node
::dir
) {
391 $srcpath =~ s
#/*$#/#;
394 open my $f,"-|","git-ls-tree","-r","-z",$gitrev,$srcpath;
398 my($m,$p) = split(/\t/,$_,2);
399 my($mode,$type,$sha1) = split(/ /,$m);
400 next if $type ne "blob";
401 if ($node_kind eq $SVN::Node
::dir
) {
402 $p = $path . substr($p,length($srcpath)-1);
406 push(@
$new,[$mode,$sha1,$p]);
409 print STDERR
"$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
413 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
414 my($author_name,$author_email,$dest);
415 my(@old,@new,@parents);
417 if (not defined $author) {
418 $author_name = $author_email = "unknown";
419 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
420 ($author_name, $author_email) = ($1, $2);
422 $author =~ s/^<(.*)>$/$1/;
423 $author_name = $author_email = $author;
425 $date = pdate
($date);
429 if($branch eq "/") { # trunk
431 } elsif($branch =~ m
#^/(.+)#) { # tag
434 } else { # "normal" branch
440 my $prev = $changed_paths->{"/"};
441 if($prev and $prev->[0] eq "A") {
442 delete $changed_paths->{"/"};
443 my $oldpath = $prev->[1];
445 if(defined $oldpath) {
447 ($parent,$p) = split_path
($revision,$oldpath);
451 $parent =~ s
#^/##; # if it's a tag
459 if($revision > $opt_s and defined $parent) {
460 open(H
,"git-rev-parse --verify $parent |");
463 print STDERR
"$revision: cannot find commit '$parent'!\n";
467 if(length($rev) != 40) {
468 print STDERR
"$revision: cannot find commit '$parent'!\n";
471 $rev = $branches{($parent eq $opt_o) ?
"/" : $parent}{"LAST"};
472 if($revision != $opt_s and not $rev) {
473 print STDERR
"$revision: do not know ancestor for '$parent'!\n";
480 # if($prev and $prev->[0] eq "A") {
482 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
483 # print STDERR "$revision: Could not create branch $branch: $!\n";
488 # or die "Could not write branch $branch: $!";
490 # or die "Could not write branch $branch: $!";
493 if(not defined $rev) {
495 } elsif ($rev ne $last_rev) {
496 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
497 system("git-read-tree", $rev);
498 die "read-tree failed for $rev: $?\n" if $?
;
502 push (@parents, $rev) if defined $rev;
505 if($tag and not %$changed_paths) {
508 my @paths = sort keys %$changed_paths;
509 foreach my $path(@paths) {
510 my $action = $changed_paths->{$path};
512 if ($action->[0] eq "R") {
513 # refer to a file/tree in an earlier commit
514 push(@old,$path); # remove any old stuff
516 if(($action->[0] eq "A") || ($action->[0] eq "R")) {
517 my $node_kind = node_kind
($branch,$path,$revision);
519 copy_path
($revision,$branch,$path,$action->[1],$action->[2],$node_kind,\
@new,\
@parents);
520 } elsif ($node_kind eq $SVN::Node
::file
) {
521 my $f = get_file
($revision,$branch,$path);
525 my $opath = $action->[3];
526 print STDERR
"$revision: $branch: could not fetch '$opath'\n";
529 } elsif ($action->[0] eq "D") {
531 } elsif ($action->[0] eq "M") {
532 my $node_kind = node_kind
($branch,$path,$revision);
533 if ($node_kind eq $SVN::Node
::file
) {
534 my $f = get_file
($revision,$branch,$path);
538 die "$revision: unknown action '".$action->[0]."' for $path\n";
543 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
555 @o2 = splice(@old,0,50);
560 system("git-update-index","--force-remove","--",@o2);
561 die "Cannot remove files: $?\n" if $?
;
567 @n2 = splice(@new,0,10);
572 system("git-update-index","--add",
573 (map { ('--cacheinfo', @
$_) } @n2));
574 die "Cannot add files: $?\n" if $?
;
577 my $pid = open(C
,"-|");
578 die "Cannot fork: $!" unless defined $pid;
580 exec("git-write-tree");
581 die "Cannot exec git-write-tree: $!\n";
583 chomp(my $tree = <C
>);
585 or die "Cannot get tree id ($tree): $!\n";
587 or die "Error running git-write-tree: $?\n";
588 print "Tree ID $tree\n" if $opt_v;
590 my $pr = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
591 my $pw = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
593 die "Fork: $!\n" unless defined $pid;
597 open(OUT
,">&STDOUT");
598 dup2
($pw->fileno(),0);
599 dup2
($pr->fileno(),1);
605 # loose detection of merges
606 # based on the commit msg
607 foreach my $rx (@mergerx) {
608 if ($message =~ $rx) {
610 if ($mparent eq 'HEAD') { $mparent = $opt_o };
611 if ( -e
"$git_dir/refs/heads/$mparent") {
612 $mparent = get_headref
($mparent, $git_dir);
613 push (@parents, $mparent);
614 print OUT
"Merge parent branch: $mparent\n" if $opt_v;
618 my %seen_parents = ();
619 my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
620 foreach my $bparent (@unique_parents) {
621 push @par, '-p', $bparent;
622 print OUT
"Merge parent branch: $bparent\n" if $opt_v;
626 "GIT_AUTHOR_NAME=$author_name",
627 "GIT_AUTHOR_EMAIL=$author_email",
628 "GIT_AUTHOR_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
629 "GIT_COMMITTER_NAME=$author_name",
630 "GIT_COMMITTER_EMAIL=$author_email",
631 "GIT_COMMITTER_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
632 "git-commit-tree", $tree,@par);
633 die "Cannot exec git-commit-tree: $!\n";
638 $message =~ s/[\s\n]+\z//;
640 print $pw "$message\n"
641 or die "Error writing to git-commit-tree: $!\n";
644 print "Committed change $revision:$branch ".strftime
("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
647 or die "Cannot get commit id ($cid): $!\n";
648 print "Commit ID $cid\n" if $opt_v;
652 die "Error running git-commit-tree: $?\n" if $?
;
655 if (not defined $cid) {
656 $cid = $branches{"/"}{"LAST"};
659 if(not defined $dest) {
660 print "... no known parent\n" if $opt_v;
662 print "Writing to refs/heads/$dest\n" if $opt_v;
663 open(C
,">$git_dir/refs/heads/$dest") and
664 print C
("$cid\n") and
666 or die "Cannot write branch $dest for update: $!\n";
670 my($in, $out) = ('','');
671 $last_rev = "-" if %$changed_paths;
672 # the tag was 'complex', i.e. did not refer to a "real" revision
674 $dest =~ tr/_/\./ if $opt_u;
677 my $pid = open2
($in, $out, 'git-mktag');
678 print $out ("object $cid\n".
681 "tagger $author_name <$author_email>\n") and
683 or die "Cannot create tag object $dest: $!\n";
688 if ( !close($in) or waitpid($pid, 0) != $pid or
689 $?
!= 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
690 die "Cannot create tag object $dest: $!\n";
693 open(C
,">$git_dir/refs/tags/$dest") and
694 print C
("$tagobj\n") and
696 or die "Cannot create tag $branch: $!\n";
698 print "Created tag '$dest' on '$branch'\n" if $opt_v;
700 $branches{$branch}{"LAST"} = $cid;
701 $branches{$branch}{$revision} = $cid;
703 print BRANCHES
"$revision $branch $cid\n";
704 print "DONE: $revision $dest $cid\n" if $opt_v;
707 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
709 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
711 while(my($path,$action) = each %$changed_paths) {
712 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
714 $changed_paths = \
%p;
723 while(my($path,$action) = each %$changed_paths) {
724 ($branch,$path) = split_path
($revision,$path);
725 next if not defined $branch;
726 $done{$branch}{$path} = $action;
728 while(($branch,$changed_paths) = each %done) {
729 commit
($branch, $changed_paths, $revision, $author, $date, $message);
733 while(++$current_rev <= $svn->{'maxrev'}) {
734 if (defined $opt_l) {
740 my $pool=SVN
::Pool
->new;
741 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,1,1,1,\
&_commit_all
,$pool);
749 if (defined $orig_git_index) {
750 $ENV{GIT_INDEX_FILE
} = $orig_git_index;
752 delete $ENV{GIT_INDEX_FILE
};
755 # Now switch back to the branch we were in before all of this happened
757 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
758 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
761 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
762 die "read-tree failed: $?\n" if $?
;
765 $orig_branch = "master";
766 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
767 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
768 unless -f
"$git_dir/refs/heads/master";
769 unlink("$git_dir/HEAD");
770 symlink("refs/heads/$orig_branch","$git_dir/HEAD");
772 system('git checkout');
773 die "checkout failed: $?\n" if $?
;
776 unlink("$git_dir/SVN2GIT_HEAD");