2f89c31e54eac82a4f0fa04c3681a2378dda82d1
1#!/usr/bin/perl -w
2
3# This tool is copyright (c) 2005, Matthias Urlichs.
4# It is released under the Gnu Public License, version 2.
5#
6# The basic idea is to pull and analyze SVN changes.
7#
8# Checking out the files is done by a single long-running SVN connection.
9#
10# The head revision is on branch "origin" by default.
11# You can change that with the '-o' option.
12
13require v5.8.0; # for shell-safe open("-|",LIST)
14use strict;
15use warnings;
16use Getopt::Std;
17use File::Spec;
18use File::Temp qw(tempfile);
19use File::Path qw(mkpath);
20use File::Basename qw(basename dirname);
21use Time::Local;
22use IO::Pipe;
23use POSIX qw(strftime dup2);
24use IPC::Open2;
25use SVN::Core;
26use SVN::Ra;
27
28die "Need CVN:Core 1.2.1 or better" if $SVN::Core::VERSION lt "1.2.1";
29
30$SIG{'PIPE'}="IGNORE";
31$ENV{'TZ'}="UTC";
32
33our($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);
34
35sub usage() {
36 print STDERR <<END;
37Usage: ${\basename $0} # fetch/update GIT from CVS
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]
41END
42 exit(1);
43}
44
45getopts("b:C:dDhil:mM:o:s:t:T:uv") or usage();
46usage if $opt_h;
47
48my $tag_name = $opt_t || "tags";
49my $trunk_name = $opt_T || "trunk";
50my $branch_name = $opt_b || "branches";
51
52@ARGV == 1 or @ARGV == 2 or usage();
53
54$opt_o ||= "origin";
55$opt_s ||= 1;
56$opt_l = 100 unless defined $opt_l;
57my $git_tree = $opt_C;
58$git_tree ||= ".";
59
60my $svn_url = $ARGV[0];
61my $svn_dir = $ARGV[1];
62
63our @mergerx = ();
64if ($opt_m) {
65 @mergerx = ( qr/\W(?:from|of|merge|merging|merged) (\w+)/i );
66}
67if ($opt_M) {
68 push (@mergerx, qr/$opt_M/);
69}
70
71select(STDERR); $|=1; select(STDOUT);
72
73
74package SVNconn;
75# Basic SVN connection.
76# We're only interested in connecting and downloading, so ...
77
78use File::Spec;
79use File::Temp qw(tempfile);
80use POSIX qw(strftime dup2);
81
82sub new {
83 my($what,$repo) = @_;
84 $what=ref($what) if ref($what);
85
86 my $self = {};
87 $self->{'buffer'} = "";
88 bless($self,$what);
89
90 $repo =~ s#/+$##;
91 $self->{'fullrep'} = $repo;
92 $self->conn();
93
94 return $self;
95}
96
97sub conn {
98 my $self = shift;
99 my $repo = $self->{'fullrep'};
100 my $s = SVN::Ra->new($repo);
101
102 die "SVN connection to $repo: $!\n" unless defined $s;
103 $self->{'svn'} = $s;
104 $self->{'repo'} = $repo;
105 $self->{'maxrev'} = $s->get_latest_revnum();
106}
107
108sub file {
109 my($self,$path,$rev) = @_;
110
111 my ($fh, $name) = tempfile('gitsvn.XXXXXX',
112 DIR => File::Spec->tmpdir(), UNLINK => 1);
113
114 print "... $rev $path ...\n" if $opt_v;
115 eval { $self->{'svn'}->get_file($path,$rev,$fh); };
116 if($@) {
117 return undef if $@ =~ /Attempted to get checksum/;
118 die $@;
119 }
120 close ($fh);
121
122 return $name;
123}
124
125package main;
126use URI;
127
128my $svn = $svn_url;
129$svn .= "/$svn_dir" if defined $svn_dir;
130$svn = SVNconn->new($svn);
131
132my $lwp_ua;
133if($opt_d or $opt_D) {
134 $svn_url = URI->new($svn_url)->canonical;
135 if($opt_D) {
136 $svn_dir =~ s#/*$#/#;
137 } else {
138 $svn_dir = "";
139 }
140 if ($svn_url->scheme eq "http") {
141 use LWP::UserAgent;
142 $lwp_ua = LWP::UserAgent->new(keep_alive => 1, requests_redirectable => []);
143 } else {
144 print STDERR "Warning: not HTTP; turning off direct file access\n";
145 $opt_d=0;
146 }
147}
148
149sub pdate($) {
150 my($d) = @_;
151 $d =~ m#(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)#
152 or die "Unparseable date: $d\n";
153 my $y=$1; $y-=1900 if $y>1900;
154 return timegm($6||0,$5,$4,$3,$2-1,$y);
155}
156
157sub getwd() {
158 my $pwd = `pwd`;
159 chomp $pwd;
160 return $pwd;
161}
162
163
164sub get_headref($$) {
165 my $name = shift;
166 my $git_dir = shift;
167 my $sha;
168
169 if (open(C,"$git_dir/refs/heads/$name")) {
170 chomp($sha = <C>);
171 close(C);
172 length($sha) == 40
173 or die "Cannot get head id for $name ($sha): $!\n";
174 }
175 return $sha;
176}
177
178
179-d $git_tree
180 or mkdir($git_tree,0777)
181 or die "Could not create $git_tree: $!";
182chdir($git_tree);
183
184my $orig_branch = "";
185my $forward_master = 0;
186my %branches;
187
188my $git_dir = $ENV{"GIT_DIR"} || ".git";
189$git_dir = getwd()."/".$git_dir unless $git_dir =~ m#^/#;
190$ENV{"GIT_DIR"} = $git_dir;
191my $orig_git_index;
192$orig_git_index = $ENV{GIT_INDEX_FILE} if exists $ENV{GIT_INDEX_FILE};
193my ($git_ih, $git_index) = tempfile('gitXXXXXX', SUFFIX => '.idx',
194 DIR => File::Spec->tmpdir());
195close ($git_ih);
196$ENV{GIT_INDEX_FILE} = $git_index;
197my $maxnum = 0;
198my $last_rev = "";
199my $last_branch;
200my $current_rev = $opt_s-1;
201unless(-d $git_dir) {
202 system("git-init-db");
203 die "Cannot init the GIT db at $git_tree: $?\n" if $?;
204 system("git-read-tree");
205 die "Cannot init an empty tree: $?\n" if $?;
206
207 $last_branch = $opt_o;
208 $orig_branch = "";
209} else {
210 -f "$git_dir/refs/heads/$opt_o"
211 or die "Branch '$opt_o' does not exist.\n".
212 "Either use the correct '-o branch' option,\n".
213 "or import to a new repository.\n";
214
215 -f "$git_dir/svn2git"
216 or die "'$git_dir/svn2git' does not exist.\n".
217 "You need that file for incremental imports.\n";
218 $last_branch = basename(readlink("$git_dir/HEAD"));
219 unless($last_branch) {
220 warn "Cannot read the last branch name: $! -- assuming 'master'\n";
221 $last_branch = "master";
222 }
223 $orig_branch = $last_branch;
224 $last_rev = get_headref($orig_branch, $git_dir);
225 if (-f "$git_dir/SVN2GIT_HEAD") {
226 die <<EOM;
227SVN2GIT_HEAD exists.
228Make sure your working directory corresponds to HEAD and remove SVN2GIT_HEAD.
229You may need to run
230
231 git-read-tree -m -u SVN2GIT_HEAD HEAD
232EOM
233 }
234 system('cp', "$git_dir/HEAD", "$git_dir/SVN2GIT_HEAD");
235
236 $forward_master =
237 $opt_o ne 'master' && -f "$git_dir/refs/heads/master" &&
238 system('cmp', '-s', "$git_dir/refs/heads/master",
239 "$git_dir/refs/heads/$opt_o") == 0;
240
241 # populate index
242 system('git-read-tree', $last_rev);
243 die "read-tree failed: $?\n" if $?;
244
245 # Get the last import timestamps
246 open my $B,"<", "$git_dir/svn2git";
247 while(<$B>) {
248 chomp;
249 my($num,$branch,$ref) = split;
250 $branches{$branch}{$num} = $ref;
251 $branches{$branch}{"LAST"} = $ref;
252 $current_rev = $num if $current_rev < $num;
253 }
254 close($B);
255}
256-d $git_dir
257 or die "Could not create git subdir ($git_dir).\n";
258
259open BRANCHES,">>", "$git_dir/svn2git";
260
261sub get_file($$$) {
262 my($rev,$branch,$path) = @_;
263
264 # revert split_path(), below
265 my $svnpath;
266 $path = "" if $path eq "/"; # this should not happen, but ...
267 if($branch eq "/") {
268 $svnpath = "/$trunk_name/$path";
269 } elsif($branch =~ m#^/#) {
270 $svnpath = "/$tag_name$branch/$path";
271 } else {
272 $svnpath = "/$branch_name/$branch/$path";
273 }
274
275 # now get it
276 my $name;
277 if($opt_d) {
278 my($req,$res);
279
280 # /svn/!svn/bc/2/django/trunk/django-docs/build.py
281 my $url=$svn_url->clone();
282 $url->path($url->path."/!svn/bc/$rev/$svn_dir$svnpath");
283 print "Fetching $url...\n" if $opt_v;
284 $req = HTTP::Request->new(GET => $url);
285 $res = $lwp_ua->request($req);
286 if ($res->is_success) {
287 my $fh;
288 ($fh, $name) = tempfile('gitsvn.XXXXXX',
289 DIR => File::Spec->tmpdir(), UNLINK => 1);
290 print $fh $res->content;
291 close($fh) or die "Could not write $name: $!\n";
292 } else {
293 return undef if $res->code == 301; # directory?
294 die $res->status_line." at $url\n";
295 }
296 } else {
297 $name = $svn->file($svnpath,$rev);
298 return undef unless defined $name;
299 }
300
301 open my $F, '-|', "git-hash-object", "-w", $name
302 or die "Cannot create object: $!\n";
303 my $sha = <$F>;
304 chomp $sha;
305 close $F;
306 unlink $name;
307 my $mode = "0644"; # SV does not seem to store any file modes
308 return [$mode, $sha, $path];
309}
310
311sub split_path($$) {
312 my($rev,$path) = @_;
313 my $branch;
314
315 if($path =~ s#^/\Q$tag_name\E/([^/]+)/?##) {
316 $branch = "/$1";
317 } elsif($path =~ s#^/\Q$trunk_name\E/?##) {
318 $branch = "/";
319 } elsif($path =~ s#^/\Q$branch_name\E/([^/]+)/?##) {
320 $branch = $1;
321 } else {
322 print STDERR "$rev: Unrecognized path: $path\n";
323 return ()
324 }
325 $path = "/" if $path eq "";
326 return ($branch,$path);
327}
328
329sub commit {
330 my($branch, $changed_paths, $revision, $author, $date, $message) = @_;
331 my($author_name,$author_email,$dest);
332 my(@old,@new);
333
334 if (not defined $author) {
335 $author_name = $author_email = "unknown";
336 } elsif ($author =~ /^(.*?)\s+<(.*)>$/) {
337 ($author_name, $author_email) = ($1, $2);
338 } else {
339 $author =~ s/^<(.*)>$/$1/;
340 $author_name = $author_email = $author;
341 }
342 $date = pdate($date);
343
344 my $tag;
345 my $parent;
346 if($branch eq "/") { # trunk
347 $parent = $opt_o;
348 } elsif($branch =~ m#^/(.+)#) { # tag
349 $tag = 1;
350 $parent = $1;
351 } else { # "normal" branch
352 # nothing to do
353 $parent = $branch;
354 }
355 $dest = $parent;
356
357 my $prev = $changed_paths->{"/"};
358 if($prev and $prev->[0] eq "A") {
359 delete $changed_paths->{"/"};
360 my $oldpath = $prev->[1];
361 my $rev;
362 if(defined $oldpath) {
363 my $p;
364 ($parent,$p) = split_path($revision,$oldpath);
365 if($parent eq "/") {
366 $parent = $opt_o;
367 } else {
368 $parent =~ s#^/##; # if it's a tag
369 }
370 } else {
371 $parent = undef;
372 }
373 }
374
375 my $rev;
376 if($revision > $opt_s and defined $parent) {
377 open(H,"git-rev-parse --verify $parent |");
378 $rev = <H>;
379 close(H) or do {
380 print STDERR "$revision: cannot find commit '$parent'!\n";
381 return;
382 };
383 chop $rev;
384 if(length($rev) != 40) {
385 print STDERR "$revision: cannot find commit '$parent'!\n";
386 return;
387 }
388 $rev = $branches{($parent eq $opt_o) ? "/" : $parent}{"LAST"};
389 if($revision != $opt_s and not $rev) {
390 print STDERR "$revision: do not know ancestor for '$parent'!\n";
391 return;
392 }
393 } else {
394 $rev = undef;
395 }
396
397# if($prev and $prev->[0] eq "A") {
398# if(not $tag) {
399# unless(open(H,"> $git_dir/refs/heads/$branch")) {
400# print STDERR "$revision: Could not create branch $branch: $!\n";
401# $state=11;
402# next;
403# }
404# print H "$rev\n"
405# or die "Could not write branch $branch: $!";
406# close(H)
407# or die "Could not write branch $branch: $!";
408# }
409# }
410 if(not defined $rev) {
411 unlink($git_index);
412 } elsif ($rev ne $last_rev) {
413 print "Switching from $last_rev to $rev ($branch)\n" if $opt_v;
414 system("git-read-tree", $rev);
415 die "read-tree failed for $rev: $?\n" if $?;
416 $last_rev = $rev;
417 }
418
419 my $cid;
420 if($tag and not %$changed_paths) {
421 $cid = $rev;
422 } else {
423 while(my($path,$action) = each %$changed_paths) {
424 if ($action->[0] eq "A") {
425 my $f = get_file($revision,$branch,$path);
426 push(@new,$f) if $f;
427 } elsif ($action->[0] eq "D") {
428 push(@old,$path);
429 } elsif ($action->[0] eq "M") {
430 my $f = get_file($revision,$branch,$path);
431 push(@new,$f) if $f;
432 } elsif ($action->[0] eq "R") {
433 # refer to a file/tree in an earlier commit
434 push(@old,$path); # remove any old stuff
435
436 # ... and add any new stuff
437 my($b,$p) = split_path($revision,$action->[1]);
438 open my $F,"-|","git-ls-tree","-r","-z", $branches{$b}{$action->[2]}, $p;
439 local $/ = '\0';
440 while(<$F>) {
441 chomp;
442 my($m,$p) = split(/\t/,$_,2);
443 my($mode,$type,$sha1) = split(/ /,$m);
444 next if $type ne "blob";
445 push(@new,[$mode,$sha1,$p]);
446 }
447 } else {
448 die "$revision: unknown action '".$action->[0]."' for $path\n";
449 }
450 }
451
452 if(@old) {
453 open my $F, "-|", "git-ls-files", "-z", @old or die $!;
454 @old = ();
455 local $/ = '\0';
456 while(<$F>) {
457 chomp;
458 push(@old,$_);
459 }
460 close($F);
461
462 while(@old) {
463 my @o2;
464 if(@old > 55) {
465 @o2 = splice(@old,0,50);
466 } else {
467 @o2 = @old;
468 @old = ();
469 }
470 system("git-update-index","--force-remove","--",@o2);
471 die "Cannot remove files: $?\n" if $?;
472 }
473 }
474 while(@new) {
475 my @n2;
476 if(@new > 12) {
477 @n2 = splice(@new,0,10);
478 } else {
479 @n2 = @new;
480 @new = ();
481 }
482 system("git-update-index","--add",
483 (map { ('--cacheinfo', @$_) } @n2));
484 die "Cannot add files: $?\n" if $?;
485 }
486
487 my $pid = open(C,"-|");
488 die "Cannot fork: $!" unless defined $pid;
489 unless($pid) {
490 exec("git-write-tree");
491 die "Cannot exec git-write-tree: $!\n";
492 }
493 chomp(my $tree = <C>);
494 length($tree) == 40
495 or die "Cannot get tree id ($tree): $!\n";
496 close(C)
497 or die "Error running git-write-tree: $?\n";
498 print "Tree ID $tree\n" if $opt_v;
499
500 my $pr = IO::Pipe->new() or die "Cannot open pipe: $!\n";
501 my $pw = IO::Pipe->new() or die "Cannot open pipe: $!\n";
502 $pid = fork();
503 die "Fork: $!\n" unless defined $pid;
504 unless($pid) {
505 $pr->writer();
506 $pw->reader();
507 open(OUT,">&STDOUT");
508 dup2($pw->fileno(),0);
509 dup2($pr->fileno(),1);
510 $pr->close();
511 $pw->close();
512
513 my @par = ();
514 @par = ("-p",$rev) if defined $rev;
515
516 # loose detection of merges
517 # based on the commit msg
518 foreach my $rx (@mergerx) {
519 if ($message =~ $rx) {
520 my $mparent = $1;
521 if ($mparent eq 'HEAD') { $mparent = $opt_o };
522 if ( -e "$git_dir/refs/heads/$mparent") {
523 $mparent = get_headref($mparent, $git_dir);
524 push @par, '-p', $mparent;
525 print OUT "Merge parent branch: $mparent\n" if $opt_v;
526 }
527 }
528 }
529
530 exec("env",
531 "GIT_AUTHOR_NAME=$author_name",
532 "GIT_AUTHOR_EMAIL=$author_email",
533 "GIT_AUTHOR_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
534 "GIT_COMMITTER_NAME=$author_name",
535 "GIT_COMMITTER_EMAIL=$author_email",
536 "GIT_COMMITTER_DATE=".strftime("+0000 %Y-%m-%d %H:%M:%S",gmtime($date)),
537 "git-commit-tree", $tree,@par);
538 die "Cannot exec git-commit-tree: $!\n";
539 }
540 $pw->writer();
541 $pr->reader();
542
543 $message =~ s/[\s\n]+\z//;
544
545 print $pw "$message\n"
546 or die "Error writing to git-commit-tree: $!\n";
547 $pw->close();
548
549 print "Committed change $revision:$branch ".strftime("%Y-%m-%d %H:%M:%S",gmtime($date)).")\n" if $opt_v;
550 chomp($cid = <$pr>);
551 length($cid) == 40
552 or die "Cannot get commit id ($cid): $!\n";
553 print "Commit ID $cid\n" if $opt_v;
554 $pr->close();
555
556 waitpid($pid,0);
557 die "Error running git-commit-tree: $?\n" if $?;
558 }
559
560 if(not defined $dest) {
561 print "... no known parent\n" if $opt_v;
562 } elsif(not $tag) {
563 print "Writing to refs/heads/$dest\n" if $opt_v;
564 open(C,">$git_dir/refs/heads/$dest") and
565 print C ("$cid\n") and
566 close(C)
567 or die "Cannot write branch $dest for update: $!\n";
568 }
569
570 if($tag) {
571 my($in, $out) = ('','');
572 $last_rev = "-" if %$changed_paths;
573 # the tag was 'complex', i.e. did not refer to a "real" revision
574
575 $dest =~ tr/_/\./ if $opt_u;
576
577 my $pid = open2($in, $out, 'git-mktag');
578 print $out ("object $cid\n".
579 "type commit\n".
580 "tag $dest\n".
581 "tagger $author_name <$author_email>\n") and
582 close($out)
583 or die "Cannot create tag object $dest: $!\n";
584
585 my $tagobj = <$in>;
586 chomp $tagobj;
587
588 if ( !close($in) or waitpid($pid, 0) != $pid or
589 $? != 0 or $tagobj !~ /^[0123456789abcdef]{40}$/ ) {
590 die "Cannot create tag object $dest: $!\n";
591 }
592
593 open(C,">$git_dir/refs/tags/$dest") and
594 print C ("$tagobj\n") and
595 close(C)
596 or die "Cannot create tag $branch: $!\n";
597
598 print "Created tag '$dest' on '$branch'\n" if $opt_v;
599 }
600 $branches{$branch}{"LAST"} = $cid;
601 $branches{$branch}{$revision} = $cid;
602 $last_rev = $cid;
603 print BRANCHES "$revision $branch $cid\n";
604 print "DONE: $revision $dest $cid\n" if $opt_v;
605}
606
607my ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
608sub _commit_all {
609 ($changed_paths, $revision, $author, $date, $message, $pool) = @_;
610 my %p;
611 while(my($path,$action) = each %$changed_paths) {
612 $p{$path} = [ $action->action,$action->copyfrom_path, $action->copyfrom_rev ];
613 }
614 $changed_paths = \%p;
615}
616
617sub commit_all {
618 my %done;
619 my @col;
620 my $pref;
621 my $branch;
622
623 while(my($path,$action) = each %$changed_paths) {
624 ($branch,$path) = split_path($revision,$path);
625 next if not defined $branch;
626 $done{$branch}{$path} = $action;
627 }
628 while(($branch,$changed_paths) = each %done) {
629 commit($branch, $changed_paths, $revision, $author, $date, $message);
630 }
631}
632
633while(++$current_rev <= $svn->{'maxrev'}) {
634 $svn->{'svn'}->get_log("/",$current_rev,$current_rev,$current_rev,1,1,\&_commit_all,"");
635 commit_all();
636 if($opt_l and not --$opt_l) {
637 print STDERR "Exiting due to a memory leak. Repeat, please.\n";
638 last;
639 }
640}
641
642
643unlink($git_index);
644
645if (defined $orig_git_index) {
646 $ENV{GIT_INDEX_FILE} = $orig_git_index;
647} else {
648 delete $ENV{GIT_INDEX_FILE};
649}
650
651# Now switch back to the branch we were in before all of this happened
652if($orig_branch) {
653 print "DONE\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
654 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
655 if $forward_master;
656 unless ($opt_i) {
657 system('git-read-tree', '-m', '-u', 'SVN2GIT_HEAD', 'HEAD');
658 die "read-tree failed: $?\n" if $?;
659 }
660} else {
661 $orig_branch = "master";
662 print "DONE; creating $orig_branch branch\n" if $opt_v and (not defined $opt_l or $opt_l > 0);
663 system("cp","$git_dir/refs/heads/$opt_o","$git_dir/refs/heads/master")
664 unless -f "$git_dir/refs/heads/master";
665 unlink("$git_dir/HEAD");
666 symlink("refs/heads/$orig_branch","$git_dir/HEAD");
667 unless ($opt_i) {
668 system('git checkout');
669 die "checkout failed: $?\n" if $?;
670 }
671}
672unlink("$git_dir/SVN2GIT_HEAD");
673close(BRANCHES);