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.
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,
34 $opt_b,$opt_r,$opt_I,$opt_A,$opt_s,$opt_l,$opt_d,$opt_D);
38 Usage: ${\basename $0} # fetch/update GIT from SVN
39 [-o branch-for-HEAD] [-h] [-v] [-l max_rev]
40 [-C GIT_repository] [-t tagname] [-T trunkname] [-b branchname]
41 [-d|-D] [-i] [-u] [-r] [-I ignorefilename] [-s start_chg]
42 [-m] [-M regex] [-A author_file] [SVN_URL]
47 getopts
("A:b:C:dDhiI:l:mM:o:rs:t:T:uv") or usage
();
50 my $tag_name = $opt_t || "tags";
51 my $trunk_name = $opt_T || "trunk";
52 my $branch_name = $opt_b || "branches";
54 @ARGV == 1 or @ARGV == 2 or usage
();
58 my $git_tree = $opt_C;
61 my $svn_url = $ARGV[0];
62 my $svn_dir = $ARGV[1];
66 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
69 push (@mergerx, qr/$opt_M/);
72 # Absolutize filename now, since we will have chdir'ed by the time we
73 # get around to opening it.
74 $opt_A = File
::Spec
->rel2abs($opt_A) if $opt_A;
77 our $users_file = undef;
79 $users_file = File
::Spec
->rel2abs(@_);
80 die "Cannot open $users_file\n" unless -f
$users_file;
81 open(my $authors,$users_file);
84 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
85 (my $user,my $name,my $email) = ($1,$2,$3);
86 $users{$user} = [$name,$email];
91 select(STDERR
); $|=1; select(STDOUT
);
95 # Basic SVN connection.
96 # We're only interested in connecting and downloading, so ...
99 use File
::Temp
qw(tempfile);
100 use POSIX
qw(strftime dup2);
101 use Fcntl
qw(SEEK_SET);
104 my($what,$repo) = @_;
105 $what=ref($what) if ref($what);
108 $self->{'buffer'} = "";
112 $self->{'fullrep'} = $repo;
120 my $repo = $self->{'fullrep'};
121 my $auth = SVN
::Core
::auth_open
([SVN
::Client
::get_simple_provider
,
122 SVN
::Client
::get_ssl_server_trust_file_provider
,
123 SVN
::Client
::get_username_provider
]);
124 my $s = SVN
::Ra
->new(url
=> $repo, auth
=> $auth);
125 die "SVN connection to $repo: $!\n" unless defined $s;
127 $self->{'repo'} = $repo;
128 $self->{'maxrev'} = $s->get_latest_revnum();
132 my($self,$path,$rev) = @_;
134 my ($fh, $name) = tempfile
('gitsvn.XXXXXX',
135 DIR
=> File
::Spec
->tmpdir(), UNLINK
=> 1);
137 print "... $rev $path ...\n" if $opt_v;
138 my (undef, $properties);
139 eval { (undef, $properties)
140 = $self->{'svn'}->get_file($path,$rev,$fh); };
142 return undef if $@
=~ /Attempted to get checksum/;
146 if (exists $properties->{'svn:executable'}) {
148 } elsif (exists $properties->{'svn:special'}) {
149 my ($special_content, $filesize);
150 $filesize = tell $fh;
151 seek $fh, 0, SEEK_SET
;
152 read $fh, $special_content, $filesize;
153 if ($special_content =~ s/^link //) {
155 seek $fh, 0, SEEK_SET
;
157 print $fh $special_content;
159 die "unexpected svn:special file encountered";
166 return ($name, $mode);
170 my($self,$path,$rev) = @_;
172 print "... $rev $path ...\n" if $opt_v;
173 my (undef,undef,$properties)
174 = $self->{'svn'}->get_dir($path,$rev,undef);
175 if (exists $properties->{'svn:ignore'}) {
176 my ($fh, $name) = tempfile
('gitsvn.XXXXXX',
177 DIR
=> File
::Spec
->tmpdir(),
179 print $fh $properties->{'svn:ignore'};
191 $svn .= "/$svn_dir" if defined $svn_dir;
192 my $svn2 = SVNconn
->new($svn);
193 $svn = SVNconn
->new($svn);
196 if($opt_d or $opt_D) {
197 $svn_url = URI
->new($svn_url)->canonical;
199 $svn_dir =~ s
#/*$#/#;
203 if ($svn_url->scheme eq "http") {
205 $lwp_ua = LWP
::UserAgent
->new(keep_alive
=> 1, requests_redirectable
=> []);
207 print STDERR
"Warning: not HTTP; turning off direct file access\n";
214 $d =~ m
#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
215 or die "Unparseable date: $d\n";
216 my $y=$1; $y-=1900 if $y>1900;
217 return timegm
($6||0,$5,$4,$3,$2-1,$y);
227 sub get_headref
($$) {
232 if (open(C
,"$git_dir/refs/heads/$name")) {
236 or die "Cannot get head id for $name ($sha): $!\n";
243 or mkdir($git_tree,0777)
244 or die "Could not create $git_tree: $!";
247 my $orig_branch = "";
248 my $forward_master = 0;
251 my $git_dir = $ENV{"GIT_DIR"} || ".git";
252 $git_dir = getwd
()."/".$git_dir unless $git_dir =~ m
#^/#;
253 $ENV{"GIT_DIR"} = $git_dir;
255 $orig_git_index = $ENV{GIT_INDEX_FILE
} if exists $ENV{GIT_INDEX_FILE
};
256 my ($git_ih, $git_index) = tempfile
('gitXXXXXX', SUFFIX
=> '.idx',
257 DIR
=> File
::Spec
->tmpdir());
259 $ENV{GIT_INDEX_FILE
} = $git_index;
263 my $current_rev = $opt_s || 1;
264 unless(-d
$git_dir) {
265 system("git-init-db");
266 die "Cannot init the GIT db at $git_tree: $?\n" if $?
;
267 system("git-read-tree");
268 die "Cannot init an empty tree: $?\n" if $?
;
270 $last_branch = $opt_o;
273 -f
"$git_dir/refs/heads/$opt_o"
274 or die "Branch '$opt_o' does not exist.\n".
275 "Either use the correct '-o branch' option,\n".
276 "or import to a new repository.\n";
278 -f
"$git_dir/svn2git"
279 or die "'$git_dir/svn2git' does not exist.\n".
280 "You need that file for incremental imports.\n";
281 open(F
, "git-symbolic-ref HEAD |") or
282 die "Cannot run git-symbolic-ref: $!\n";
283 chomp ($last_branch = <F
>);
284 $last_branch = basename
($last_branch);
286 unless($last_branch) {
287 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
288 $last_branch = "master";
290 $orig_branch = $last_branch;
291 $last_rev = get_headref
($orig_branch, $git_dir);
292 if (-f
"$git_dir/SVN2GIT_HEAD") {
295 Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
298 git-read-tree -m -u SVN2GIT_HEAD HEAD
301 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
304 $opt_o ne 'master' && -f
"$git_dir/refs/heads/master" &&
305 system('cmp', '-s', "$git_dir/refs/heads/master",
306 "$git_dir/refs/heads/$opt_o") == 0;
309 system('git-read-tree', $last_rev);
310 die "read-tree failed: $?\n" if $?
;
312 # Get the last import timestamps
313 open my $B,"<", "$git_dir/svn2git";
316 my($num,$branch,$ref) = split;
317 $branches{$branch}{$num} = $ref;
318 $branches{$branch}{"LAST"} = $ref;
319 $current_rev = $num+1 if $current_rev <= $num;
324 or die "Could not create git subdir ($git_dir).\n";
326 my $default_authors = "$git_dir/svn-authors";
329 copy
($opt_A,$default_authors) or die "Copy failed: $!";
331 read_users
($default_authors) if -f
$default_authors;
334 open BRANCHES
,">>", "$git_dir/svn2git";
337 my ($branch, $path, $revision) = @_;
338 my $pool=SVN
::Pool
->new;
339 my $kind = $svn->{'svn'}->check_path(revert_split_path
($branch,$path),$revision,$pool);
344 sub revert_split_path
($$) {
345 my($branch,$path) = @_;
348 $path = "" if $path eq "/"; # this should not happen, but ...
350 $svnpath = "$trunk_name/$path";
351 } elsif($branch =~ m
#^/#) {
352 $svnpath = "$tag_name$branch/$path";
354 $svnpath = "$branch_name/$branch/$path";
362 my($rev,$branch,$path) = @_;
364 my $svnpath = revert_split_path
($branch,$path);
371 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
372 my $url=$svn_url->clone();
373 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
374 print "... $path...\n" if $opt_v;
375 $req = HTTP
::Request
->new(GET
=> $url);
376 $res = $lwp_ua->request($req);
377 if ($res->is_success) {
379 ($fh, $name) = tempfile
('gitsvn.XXXXXX',
380 DIR
=> File
::Spec
->tmpdir(), UNLINK
=> 1);
381 print $fh $res->content;
382 close($fh) or die "Could not write $name: $!\n";
384 return undef if $res->code == 301; # directory?
385 die $res->status_line." at $url\n";
387 $mode = '0644'; # can't obtain mode via direct http request?
389 ($name,$mode) = $svn->file("$svnpath",$rev);
390 return undef unless defined $name;
393 my $pid = open(my $F, '-|');
394 die $! unless defined $pid;
396 exec("git-hash-object", "-w", $name)
397 or die "Cannot create object: $!\n";
403 return [$mode, $sha, $path];
406 sub get_ignore
($$$$$) {
407 my($new,$old,$rev,$branch,$path) = @_;
409 return unless $opt_I;
410 my $svnpath = revert_split_path
($branch,$path);
411 my $name = $svn->ignore("$svnpath",$rev);
415 $path = File
::Spec
->catfile($path,$opt_I);
418 my $pid = open(my $F, '-|');
419 die $! unless defined $pid;
421 exec("git-hash-object", "-w", $name)
422 or die "Cannot create object: $!\n";
428 push(@
$new,['0644',$sha,$path]);
438 if($path =~ s
#^/\Q$tag_name\E/([^/]+)/?##) {
440 } elsif($path =~ s
#^/\Q$trunk_name\E/?##) {
442 } elsif($path =~ s
#^/\Q$branch_name\E/([^/]+)/?##) {
450 print STDERR
"$rev: Unrecognized path: $path\n" unless (defined $no_error{$path});
453 $path = "/" if $path eq "";
454 return ($branch,$path);
459 my ($srcbranch,$uptorev) = @_;
461 my $bbranches = $branches{$srcbranch};
462 my @revs = reverse sort { ($a eq 'LAST' ?
0 : $a) <=> ($b eq 'LAST' ?
0 : $b) } keys %$bbranches;
464 foreach my $arev(@revs) {
465 next if ($arev eq 'LAST');
466 if ($arev <= $uptorev) {
474 sub copy_path
($$$$$$$$) {
475 # Somebody copied a whole subdirectory.
476 # We need to find the index entries from the old version which the
477 # SVN log entry points to, and add them to the new place.
479 my($newrev,$newbranch,$path,$oldpath,$rev,$node_kind,$new,$parents) = @_;
481 my($srcbranch,$srcpath) = split_path
($rev,$oldpath);
482 unless(defined $srcbranch) {
483 print "Path not found when copying from $oldpath @ $rev\n";
486 my $therev = branch_rev
($srcbranch, $rev);
487 my $gitrev = $branches{$srcbranch}{$therev};
489 print STDERR
"$newrev:$newbranch: could not find $oldpath \@ $rev\n";
492 if ($srcbranch ne $newbranch) {
493 push(@
$parents, $branches{$srcbranch}{'LAST'});
495 print "$newrev:$newbranch:$path: copying from $srcbranch:$srcpath @ $rev\n" if $opt_v;
496 if ($node_kind eq $SVN::Node
::dir
) {
497 $srcpath =~ s
#/*$#/#;
500 my $pid = open my $f,'-|';
501 die $! unless defined $pid;
503 exec("git-ls-tree","-r","-z",$gitrev,$srcpath)
509 my($m,$p) = split(/\t/,$_,2);
510 my($mode,$type,$sha1) = split(/ /,$m);
511 next if $type ne "blob";
512 if ($node_kind eq $SVN::Node
::dir
) {
513 $p = $path . substr($p,length($srcpath)-1);
517 push(@
$new,[$mode,$sha1,$p]);
520 print STDERR
"$newrev:$newbranch: could not list files in $oldpath \@ $rev\n";
524 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
525 my($author_name,$author_email,$dest);
526 my(@old,@new,@parents);
528 if (not defined $author) {
529 $author_name = $author_email = "unknown";
530 } elsif (defined $users_file) {
531 die "User $author is not listed in $users_file\n"
532 unless exists $users{$author};
533 ($author_name,$author_email) = @
{$users{$author}};
534 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
535 ($author_name, $author_email) = ($1, $2);
537 $author =~ s/^<(.*)>$/$1/;
538 $author_name = $author_email = $author;
540 $date = pdate
($date);
544 if($branch eq "/") { # trunk
546 } elsif($branch =~ m
#^/(.+)#) { # tag
549 } else { # "normal" branch
555 my $prev = $changed_paths->{"/"};
556 if($prev and $prev->[0] eq "A") {
557 delete $changed_paths->{"/"};
558 my $oldpath = $prev->[1];
560 if(defined $oldpath) {
562 ($parent,$p) = split_path
($revision,$oldpath);
566 $parent =~ s
#^/##; # if it's a tag
574 if($revision > $opt_s and defined $parent) {
575 open(H
,"git-rev-parse --verify $parent |");
578 print STDERR
"$revision: cannot find commit '$parent'!\n";
582 if(length($rev) != 40) {
583 print STDERR
"$revision: cannot find commit '$parent'!\n";
586 $rev = $branches{($parent eq $opt_o) ?
"/" : $parent}{"LAST"};
587 if($revision != $opt_s and not $rev) {
588 print STDERR
"$revision: do not know ancestor for '$parent'!\n";
595 # if($prev and $prev->[0] eq "A") {
597 # unless(open(H,"> $git_dir/refs/heads/$branch")) {
598 # print STDERR "$revision: Could not create branch $branch: $!\n";
603 # or die "Could not write branch $branch: $!";
605 # or die "Could not write branch $branch: $!";
608 if(not defined $rev) {
610 } elsif ($rev ne $last_rev) {
611 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
612 system("git-read-tree", $rev);
613 die "read-tree failed for $rev: $?\n" if $?
;
617 push (@parents, $rev) if defined $rev;
620 if($tag and not %$changed_paths) {
623 my @paths = sort keys %$changed_paths;
624 foreach my $path(@paths) {
625 my $action = $changed_paths->{$path};
627 if ($action->[0] eq "R") {
628 # refer to a file/tree in an earlier commit
629 push(@old,$path); # remove any old stuff
631 if(($action->[0] eq "A") || ($action->[0] eq "R")) {
632 my $node_kind = node_kind
($branch,$path,$revision);
633 if ($node_kind eq $SVN::Node
::file
) {
634 my $f = get_file
($revision,$branch,$path);
638 my $opath = $action->[3];
639 print STDERR
"$revision: $branch: could not fetch '$opath'\n";
641 } elsif ($node_kind eq $SVN::Node
::dir
) {
643 copy_path
($revision, $branch,
645 $action->[2], $node_kind,
648 get_ignore
(\
@new, \
@old, $revision,
652 } elsif ($action->[0] eq "D") {
654 } elsif ($action->[0] eq "M") {
655 my $node_kind = node_kind
($branch,$path,$revision);
656 if ($node_kind eq $SVN::Node
::file
) {
657 my $f = get_file
($revision,$branch,$path);
659 } elsif ($node_kind eq $SVN::Node
::dir
) {
660 get_ignore
(\
@new, \
@old, $revision,
664 die "$revision: unknown action '".$action->[0]."' for $path\n";
671 @o1 = splice(@old,0,50);
676 my $pid = open my $F, "-|";
677 die "$!" unless defined $pid;
679 exec("git-ls-files", "-z", @o1) or die $!;
692 @o2 = splice(@o1,0,50);
697 system("git-update-index","--force-remove","--",@o2);
698 die "Cannot remove files: $?\n" if $?
;
704 @n2 = splice(@new,0,10);
709 system("git-update-index","--add",
710 (map { ('--cacheinfo', @
$_) } @n2));
711 die "Cannot add files: $?\n" if $?
;
714 my $pid = open(C
,"-|");
715 die "Cannot fork: $!" unless defined $pid;
717 exec("git-write-tree");
718 die "Cannot exec git-write-tree: $!\n";
720 chomp(my $tree = <C
>);
722 or die "Cannot get tree id ($tree): $!\n";
724 or die "Error running git-write-tree: $?\n";
725 print "Tree ID $tree\n" if $opt_v;
727 my $pr = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
728 my $pw = IO
::Pipe
->new() or die "Cannot open pipe: $!\n";
730 die "Fork: $!\n" unless defined $pid;
734 open(OUT
,">&STDOUT");
735 dup2
($pw->fileno(),0);
736 dup2
($pr->fileno(),1);
742 # loose detection of merges
743 # based on the commit msg
744 foreach my $rx (@mergerx) {
745 if ($message =~ $rx) {
747 if ($mparent eq 'HEAD') { $mparent = $opt_o };
748 if ( -e
"$git_dir/refs/heads/$mparent") {
749 $mparent = get_headref
($mparent, $git_dir);
750 push (@parents, $mparent);
751 print OUT
"Merge parent branch: $mparent\n" if $opt_v;
755 my %seen_parents = ();
756 my @unique_parents = grep { ! $seen_parents{$_} ++ } @parents;
757 foreach my $bparent (@unique_parents) {
758 push @par, '-p', $bparent;
759 print OUT
"Merge parent branch: $bparent\n" if $opt_v;
763 "GIT_AUTHOR_NAME=$author_name",
764 "GIT_AUTHOR_EMAIL=$author_email",
765 "GIT_AUTHOR_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
766 "GIT_COMMITTER_NAME=$author_name",
767 "GIT_COMMITTER_EMAIL=$author_email",
768 "GIT_COMMITTER_DATE=".strftime
("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
769 "git-commit-tree", $tree,@par);
770 die "Cannot exec git-commit-tree: $!\n";
775 $message =~ s/[\s\n]+\z//;
776 $message = "r$revision: $message" if $opt_r;
778 print $pw "$message\n"
779 or die "Error writing to git-commit-tree: $!\n";
782 print "Committed change $revision:$branch ".strftime
("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
785 or die "Cannot get commit id ($cid): $!\n";
786 print "Commit ID $cid\n" if $opt_v;
790 die "Error running git-commit-tree: $?\n" if $?
;
793 if (not defined $cid) {
794 $cid = $branches{"/"}{"LAST"};
797 if(not defined $dest) {
798 print "... no known parent\n" if $opt_v;
800 print "Writing to refs/heads/$dest\n" if $opt_v;
801 open(C
,">$git_dir/refs/heads/$dest") and
802 print C
("$cid\n") and
804 or die "Cannot write branch $dest for update: $!\n";
808 my($in, $out) = ('','');
809 $last_rev = "-" if %$changed_paths;
810 # the tag was 'complex', i.e. did not refer to a "real" revision
812 $dest =~ tr/_/\./ if $opt_u;
815 my $pid = open2
($in, $out, 'git-mktag');
816 print $out ("object $cid\n".
819 "tagger $author_name <$author_email>\n") and
821 or die "Cannot create tag object $dest: $!\n";
826 if ( !close($in) or waitpid($pid, 0) != $pid or
827 $?
!= 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
828 die "Cannot create tag object $dest: $!\n";
831 open(C
,">$git_dir/refs/tags/$dest") and
832 print C
("$tagobj\n") and
834 or die "Cannot create tag $branch: $!\n";
836 print "Created tag '$dest' on '$branch'\n" if $opt_v;
838 $branches{$branch}{"LAST"} = $cid;
839 $branches{$branch}{$revision} = $cid;
841 print BRANCHES
"$revision $branch $cid\n";
842 print "DONE: $revision $dest $cid\n" if $opt_v;
846 # Recursive use of the SVN connection does not work
849 my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
851 while(my($path,$action) = each %$changed_paths) {
852 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev, $path ];
854 $changed_paths = \
%p;
861 while(my($path,$action) = each %$changed_paths) {
862 ($branch,$path) = split_path
($revision,$path);
863 next if not defined $branch;
864 $done{$branch}{$path} = $action;
866 while(($branch,$changed_paths) = each %done) {
867 commit
($branch, $changed_paths, $revision, $author, $date, $message);
871 $opt_l = $svn->{'maxrev'} if not defined $opt_l or $opt_l > $svn->{'maxrev'};
873 if ($opt_l < $current_rev) {
874 print "Up to date: no new revisions to fetch!\n" if $opt_v;
875 unlink("$git_dir/SVN2GIT_HEAD");
879 print "Fetching from $current_rev to $opt_l ...\n" if $opt_v;
881 my $pool=SVN
::Pool
->new;
882 $svn->{'svn'}->get_log("/",$current_rev,$opt_l,0,1,1,\
&commit_all
,$pool);
888 if (defined $orig_git_index) {
889 $ENV{GIT_INDEX_FILE
} = $orig_git_index;
891 delete $ENV{GIT_INDEX_FILE
};
894 # Now switch back to the branch we were in before all of this happened
896 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
897 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
900 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
901 die "read-tree failed: $?\n" if $?
;
904 $orig_branch = "master";
905 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
906 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
907 unless -f
"$git_dir/refs/heads/master";
908 system('git-update-ref', 'HEAD', "$orig_branch");
910 system('git checkout');
911 die "checkout failed: $?\n" if $?
;
914 unlink("$git_dir/SVN2GIT_HEAD");