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_r,$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_rev]
39 [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
40 [-d|-D] [-i] [-u] [-r] [-s start_chg] [-m] [-M regex] [SVN_URL]
45 getopts
("b:C:dDhil:mM:o:rs: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 $auth = SVN
::Core
::auth_open
([SVN
::Client
::get_simple_provider
,
100 SVN
::Client
::get_ssl_server_trust_file_provider
,
101 SVN
::Client
::get_username_provider
]);
102 my $s = SVN
::Ra
->new(url
=> $repo, auth
=> $auth);
103 die "SVN connection to $repo: $!\n" unless defined $s;
105 $self->{'repo'} = $repo;
106 $self->{'maxrev'} = $s->get_latest_revnum();
110 my($self,$path,$rev) = @_;
112 my ($fh, $name) = tempfile
('gitsvn.XXXXXX',
113 DIR
=> File
::Spec
->tmpdir(), UNLINK
=> 1);
115 print "... $rev $path ...\n" if $opt_v;
116 my $pool = SVN
::Pool
->new();
117 eval { $self->{'svn'}->get_file($path,$rev,$fh,$pool); };
120 return undef if $@
=~ /Attempted to get checksum/;
132 $svn .= "/$svn_dir" if defined $svn_dir;
133 my $svn2 = SVNconn
->new($svn);
134 $svn = SVNconn
->new($svn);
137 if($opt_d or $opt_D) {
138 $svn_url = URI
->new($svn_url)->canonical;
140 $svn_dir =~ s
#/*$#/#;
144 if ($svn_url->scheme eq "http") {
146 $lwp_ua = LWP
::UserAgent
->new(keep_alive
=> 1, requests_redirectable
=> []);
148 print STDERR
"Warning: not HTTP; turning off direct file access\n";
155 $d =~ m
#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
156 or die "Unparseable date: $d\n";
157 my $y=$1; $y-=1900 if $y>1900;
158 return timegm
($6||0,$5,$4,$3,$2-1,$y);
168 sub get_headref
($$) {
173 if (open(C
,"$git_dir/refs/heads/$name")) {
177 or die "Cannot get head id for $name ($sha): $!\n";
184 or mkdir($git_tree,0777)
185 or die "Could not create $git_tree: $!";
188 my $orig_branch = "";
189 my $forward_master = 0;
192 my $git_dir = $ENV{"GIT_DIR"} || ".git";
193 $git_dir = getwd
()."/".$git_dir unless $git_dir =~ m
#^/#;
194 $ENV{"GIT_DIR"} = $git_dir;
196 $orig_git_index = $ENV{GIT_INDEX_FILE
} if exists $ENV{GIT_INDEX_FILE
};
197 my ($git_ih, $git_index) = tempfile
('gitXXXXXX', SUFFIX
=> '.idx',
198 DIR
=> File
::Spec
->tmpdir());
200 $ENV{GIT_INDEX_FILE
} = $git_index;
204 my $current_rev = $opt_s || 1;
205 unless(-d
$git_dir) {
206 system("git-init-db");
207 die "Cannot init the GIT db at $git_tree: $?\n" if $?
;
208 system("git-read-tree");
209 die "Cannot init an empty tree: $?\n" if $?
;
211 $last_branch = $opt_o;
214 -f
"$git_dir/refs/heads/$opt_o"
215 or die "Branch '$opt_o' does not exist.\n".
216 "Either use the correct '-o branch' option,\n".
217 "or import to a new repository.\n";
219 -f
"$git_dir/svn2git"
220 or die "'$git_dir/svn2git' does not exist.\n".
221 "You need that file for incremental imports.\n";
222 open(F
, "git-symbolic-ref HEAD |") or
223 die "Cannot run git-symbolic-ref: $!\n";
224 chomp ($last_branch = <F
>);
225 $last_branch = basename
($last_branch);
227 unless($last_branch) {
228 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
229 $last_branch = "master";
231 $orig_branch = $last_branch;
232 $last_rev = get_headref
($orig_branch, $git_dir);
233 if (-f
"$git_dir/SVN2GIT_HEAD") {
236 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
239 git-read-tree -m -u SVN2GIT_HEAD HEAD
242 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
245 $opt_o ne 'master' && -f
"$git_dir/refs/heads/master" &&
246 system('cmp', '-s', "$git_dir/refs/heads/master",
247 "$git_dir/refs/heads/$opt_o") == 0;
250 system('git-read-tree', $last_rev);
251 die "read-tree failed: $?\n" if $?
;
253 # Get the last import timestamps
254 open my $B,"<", "$git_dir/svn2git";
257 my($num,$branch,$ref) = split;
258 $branches{$branch}{$num} = $ref;
259 $branches{$branch}{"LAST"} = $ref;
260 $current_rev = $num+1 if $current_rev <= $num;
265 or die "Could not create git subdir ($git_dir).\n";
267 open BRANCHES
,">>", "$git_dir/svn2git";
270 my ($branch, $path, $revision) = @_;
271 my $pool=SVN
::Pool
->new;
272 my $kind = $svn->{'svn'}->check_path(revert_split_path
($branch,$path),$revision,$pool);
277 sub revert_split_path
($$) {
278 my($branch,$path) = @_;
281 $path = "" if $path eq "/"; # this should not happen, but ...
283 $svnpath = "$trunk_name/$path";
284 } elsif($branch =~ m
#^/#) {
285 $svnpath = "$tag_name$branch/$path";
287 $svnpath = "$branch_name/$branch/$path";
295 my($rev,$branch,$path) = @_;
297 my $svnpath = revert_split_path
($branch,$path);
304 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
305 my $url=$svn_url->clone();
306 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
307 print "... $path...\n" if $opt_v;
308 $req = HTTP
::Request
->new(GET
=> $url);
309 $res = $lwp_ua->request($req);
310 if ($res->is_success) {
312 ($fh, $name) = tempfile
('gitsvn.XXXXXX',
313 DIR
=> File
::Spec
->tmpdir(), UNLINK
=> 1);
314 print $fh $res->content;
315 close($fh) or die "Could not write $name: $!\n";
317 return undef if $res->code == 301; # directory?
318 die $res->status_line." at $url\n";
321 $name = $svn->file("$svnpath",$rev);
322 return undef unless defined $name;
325 open my $F, '-|', "git-hash-object", "-w", $name
326 or die "Cannot create object: $!\n";
331 my $mode = "0644"; # SV does not seem to store any file modes
332 return [$mode, $sha, $path];
339 if($path =~ s
#^/\Q$tag_name\E/([^/]+)/?##) {
341 } elsif($path =~ s
#^/\Q$trunk_name\E/?##) {
343 } elsif($path =~ s
#^/\Q$branch_name\E/([^/]+)/?##) {
351 print STDERR
"$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
354 $path = "/" if $path eq "";
355 return ($branch,$path);
360 my ($srcbranch,$uptorev) = @_;
362 my $bbranches = $branches{$srcbranch};
363 my @revs = reverse sort { ($a eq 'LAST' ?
0 : $a) <=> ($b eq 'LAST' ?
0 : $b) } keys %$bbranches;
365 foreach my $arev(@revs) {
366 next if ($arev eq 'LAST');
367 if ($arev <= $uptorev) {
375 sub copy_path
($$$$$$$$) {
376 # Somebody copied a whole subdirectory.
377 # We need to find the index entries from the old version which the
378 # SVN log entry points to, and add them to the new place.
380 my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
382 my($srcbranch,$srcpath) = split_path
($rev,$oldpath);
383 unless(defined $srcbranch) {
384 print "Path not found when copying from $oldpath @ $rev\n";
387 my $therev = branch_rev
($srcbranch, $rev);
388 my $gitrev = $branches{$srcbranch}{$therev};
390 print STDERR
"$newrev:$newbranch: could not find $oldpath \@ $rev\n";
393 if ($srcbranch ne $newbranch) {
394 push(@
$parents, $branches{$srcbranch}{'LAST'});
396 print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
397 if ($node_kind eq $SVN::Node
::dir
) {
398 $srcpath =~ s
#/*$#/#;
401 open my $f,"-|","git-ls-tree","-r","-z",$gitrev,$srcpath;
405 my($m,$p) = split(/\t/,$_,2);
406 my($mode,$type,$sha1) = split(/ /,$m);
407 next if $type ne "blob";
408 if ($node_kind eq $SVN::Node
::dir
) {
409 $p = $path . substr($p,length($srcpath)-1);
413 push(@
$new,[$mode,$sha1,$p]);
416 print STDERR
"$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
420 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
421 my($author_name,$author_email,$dest);
422 my(@old,@new,@parents);
424 if (not defined $author) {
425 $author_name = $author_email = "unknown";
426 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
427 ($author_name, $author_email) = ($1, $2);
429 $author =~ s/^<(.*)>$/$1/;
430 $author_name = $author_email = $author;
432 $date = pdate
($date);
436 if($branch eq "/") { # trunk
438 } elsif($branch =~ m
#^/(.+)#) { # tag
441 } else { # "normal" branch
447 my $prev = $changed_paths->{"/"};
448 if($prev and $prev->[0] eq "A") {
449 delete $changed_paths->{"/"};
450 my $oldpath = $prev->[1];
452 if(defined $oldpath) {
454 ($parent,$p) = split_path
($revision,$oldpath);
458 $parent =~ s
#^/##; # if it's a tag
466 if($revision > $opt_s and defined $parent) {
467 open(H
,"git-rev-parse --verify $parent |");
470 print STDERR
"$revision: cannot find commit '$parent'!\n";
474 if(length($rev) != 40) {
475 print STDERR
"$revision: cannot find commit '$parent'!\n";
478 $rev = $branches{($parent eq $opt_o) ?
"/" : $parent}{"LAST"};
479 if($revision != $opt_s and not $rev) {
480 print STDERR
"$revision: do not know ancestor for '$parent'!\n";
487 # if($prev and $prev->[0] eq "A") {
489 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
490 # print STDERR "$revision: Could not create branch $branch: $!\n";
495 # or die "Could not write branch $branch: $!";
497 # or die "Could not write branch $branch: $!";
500 if(not defined $rev) {
502 } elsif ($rev ne $last_rev) {
503 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
504 system("git-read-tree", $rev);
505 die "read-tree failed for $rev: $?\n" if $?
;
509 push (@parents, $rev) if defined $rev;
512 if($tag and not %$changed_paths) {
515 my @paths = sort keys %$changed_paths;
516 foreach my $path(@paths) {
517 my $action = $changed_paths->{$path};
519 if ($action->[0] eq "R") {
520 # refer to a file/tree in an earlier commit
521 push(@old,$path); # remove any old stuff
523 if(($action->[0] eq "A") || ($action->[0] eq "R")) {
524 my $node_kind = node_kind
($branch,$path,$revision);
526 copy_path
($revision,$branch,$path,$action->[1],$action->[2],$node_kind,\
@new,\
@parents);
527 } elsif ($node_kind eq $SVN::Node
::file
) {
528 my $f = get_file
($revision,$branch,$path);
532 my $opath = $action->[3];
533 print STDERR
"$revision: $branch: could not fetch '$opath'\n";
536 } elsif ($action->[0] eq "D") {
538 } elsif ($action->[0] eq "M") {
539 my $node_kind = node_kind
($branch,$path,$revision);
540 if ($node_kind eq $SVN::Node
::file
) {
541 my $f = get_file
($revision,$branch,$path);
545 die "$revision: unknown action '".$action->[0]."' for $path\n";
552 @o1 = splice(@old,0,50);
557 open my $F, "-|", "git-ls-files", "-z", @o1 or die $!;
569 @o2 = splice(@o1,0,50);
574 system("git-update-index","--force-remove","--",@o2);
575 die "Cannot remove files: $?\n" if $?
;
581 @n2 = splice(@new,0,10);
586 system("git-update-index","--add",
587 (map { ('--cacheinfo', @
$_) } @n2));
588 die "Cannot add files: $?\n" if $?
;
591 my $pid = open(C
,"-|");
592 die "Cannot fork: $!" unless defined $pid;
594 exec("git-write-tree");
595 die "Cannot exec git-write-tree: $!\n";
597 chomp(my $tree = <C
>);
599 or die "Cannot get tree id ($tree): $!\n";
601 or die "Error running git-write-tree: $?\n";
602 print "Tree ID $tree\n" if $opt_v;
604 my $pr = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
605 my $pw = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
607 die "Fork: $!\n" unless defined $pid;
611 open(OUT
,">&STDOUT");
612 dup2
($pw->fileno(),0);
613 dup2
($pr->fileno(),1);
619 # loose detection of merges
620 # based on the commit msg
621 foreach my $rx (@mergerx) {
622 if ($message =~ $rx) {
624 if ($mparent eq 'HEAD') { $mparent = $opt_o };
625 if ( -e
"$git_dir/refs/heads/$mparent") {
626 $mparent = get_headref
($mparent, $git_dir);
627 push (@parents, $mparent);
628 print OUT
"Merge parent branch: $mparent\n" if $opt_v;
632 my %seen_parents = ();
633 my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
634 foreach my $bparent (@unique_parents) {
635 push @par, '-p', $bparent;
636 print OUT
"Merge parent branch: $bparent\n" if $opt_v;
640 "GIT_AUTHOR_NAME=$author_name",
641 "GIT_AUTHOR_EMAIL=$author_email",
642 "GIT_AUTHOR_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
643 "GIT_COMMITTER_NAME=$author_name",
644 "GIT_COMMITTER_EMAIL=$author_email",
645 "GIT_COMMITTER_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
646 "git-commit-tree", $tree,@par);
647 die "Cannot exec git-commit-tree: $!\n";
652 $message =~ s/[\s\n]+\z//;
653 $message = "r$revision: $message" if $opt_r;
655 print $pw "$message\n"
656 or die "Error writing to git-commit-tree: $!\n";
659 print "Committed change $revision:$branch ".strftime
("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
662 or die "Cannot get commit id ($cid): $!\n";
663 print "Commit ID $cid\n" if $opt_v;
667 die "Error running git-commit-tree: $?\n" if $?
;
670 if (not defined $cid) {
671 $cid = $branches{"/"}{"LAST"};
674 if(not defined $dest) {
675 print "... no known parent\n" if $opt_v;
677 print "Writing to refs/heads/$dest\n" if $opt_v;
678 open(C
,">$git_dir/refs/heads/$dest") and
679 print C
("$cid\n") and
681 or die "Cannot write branch $dest for update: $!\n";
685 my($in, $out) = ('','');
686 $last_rev = "-" if %$changed_paths;
687 # the tag was 'complex', i.e. did not refer to a "real" revision
689 $dest =~ tr/_/\./ if $opt_u;
692 my $pid = open2
($in, $out, 'git-mktag');
693 print $out ("object $cid\n".
696 "tagger $author_name <$author_email>\n") and
698 or die "Cannot create tag object $dest: $!\n";
703 if ( !close($in) or waitpid($pid, 0) != $pid or
704 $?
!= 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
705 die "Cannot create tag object $dest: $!\n";
708 open(C
,">$git_dir/refs/tags/$dest") and
709 print C
("$tagobj\n") and
711 or die "Cannot create tag $branch: $!\n";
713 print "Created tag '$dest' on '$branch'\n" if $opt_v;
715 $branches{$branch}{"LAST"} = $cid;
716 $branches{$branch}{$revision} = $cid;
718 print BRANCHES
"$revision $branch $cid\n";
719 print "DONE: $revision $dest $cid\n" if $opt_v;
723 # Recursive use of the SVN connection does not work
726 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
728 while(my($path,$action) = each %$changed_paths) {
729 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
731 $changed_paths = \
%p;
738 while(my($path,$action) = each %$changed_paths) {
739 ($branch,$path) = split_path
($revision,$path);
740 next if not defined $branch;
741 $done{$branch}{$path} = $action;
743 while(($branch,$changed_paths) = each %done) {
744 commit
($branch, $changed_paths, $revision, $author, $date, $message);
748 $opt_l = $svn->{'maxrev'} if not defined $opt_l or $opt_l > $svn->{'maxrev'};
750 if ($svn->{'maxrev'} < $current_rev) {
751 print "Up to date: no new revisions to fetch!\n" if $opt_v;
752 unlink("$git_dir/SVN2GIT_HEAD");
756 print "Fetching from $current_rev to $opt_l ...\n" if $opt_v;
758 my $pool=SVN
::Pool
->new;
759 $svn->{'svn'}->get_log("/",$current_rev,$opt_l,0,1,1,\
&commit_all
,$pool);
765 if (defined $orig_git_index) {
766 $ENV{GIT_INDEX_FILE
} = $orig_git_index;
768 delete $ENV{GIT_INDEX_FILE
};
771 # Now switch back to the branch we were in before all of this happened
773 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
774 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
777 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
778 die "read-tree failed: $?\n" if $?
;
781 $orig_branch = "master";
782 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
783 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
784 unless -f
"$git_dir/refs/heads/master";
785 system('git-update-ref', 'HEAD', "$orig_branch");
787 system('git checkout');
788 die "checkout failed: $?\n" if $?
;
791 unlink("$git_dir/SVN2GIT_HEAD");