4 use vars qw/ $AUTHOR $VERSION
5 $SVN_URL $SVN_INFO $SVN_WC
6 $GIT_SVN_INDEX $GIT_SVN
8 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
11 $GIT_SVN = $ENV{GIT_SVN_ID} || 'git-svn';
12 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
13 $ENV{GIT_DIR} ||= $GIT_DIR;
15 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
16 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
18 # make sure the svn binary gives consistent output between locales and TZs:
22 # If SVN:: library support is added, please make the dependencies
23 # optional and preserve the capability to use the command-line client.
24 # use eval { require SVN::... } to make it lazy load
27 use File::Basename qw/dirname basename/;
28 use File::Path qw/mkpath/;
29 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
31 my $sha1 = qr/[a-f\d]{40}/;
32 my $sha1_short = qr/[a-f\d]{6,40}/;
33 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
34 $_find_copies_harder, $_l);
36 GetOptions( 'revision|r=s' => \$_revision,
37 'no-ignore-externals' => \$_no_ignore_ext,
41 'help|H|h' => \$_help,
42 'find-copies-harder' => \$_find_copies_harder,
44 'no-stop-on-copy' => \$_no_stop_copy );
46 fetch => [ \&fetch, "Download new revisions from SVN" ],
47 init => [ \&init, "Initialize and fetch (import)"],
48 commit => [ \&commit, "Commit git revisions to SVN" ],
49 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)" ],
50 help => [ \&usage, "Show help" ],
53 for (my $i = 0; $i < @ARGV; $i++) {
54 if (defined $cmd{$ARGV[$i]}) {
61 # we may be called as git-svn-(command), or git-svn(command).
63 if (/git\-svn\-?($_)(?:\.\w+)?$/) {
69 usage(1) unless (defined $cmd);
70 svn_check_ignore_externals();
71 $cmd{$cmd}->[0]->(@ARGV);
74 ####################### primary functions ######################
76 my $exit = shift || 0;
77 my $fd = $exit ? \*STDERR : \*STDOUT;
79 git-svn - bidirectional operations between a single Subversion tree and git
80 Usage: $0 <command> [options] [arguments]\n
83 foreach (sort keys %cmd) {
84 print $fd ' ',pack('A10',$_),$cmd{$_}->[1],"\n";
87 \nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
88 you're tracking multiple SVN branches/repositories in one git repository
89 and want to keep them separate.
95 $SVN_URL = shift or undef;
99 my $pid = open(my $rev_list,'-|');
100 defined $pid or croak $!;
102 exec("git-rev-list","$GIT_SVN-HEAD") or croak $!;
105 while (<$rev_list>) {
108 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
109 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
110 next if (!@commit); # skip merges
111 my $id = $commit[$#commit];
112 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
114 if (!$rev || !$uuid || !$url) {
115 # some of the original repositories I made had
116 # indentifiers like this:
117 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
119 if (!$rev || !$uuid) {
120 croak "Unable to extract revision or UUID from ",
124 print "r$rev = $c\n";
125 unless (defined $first) {
126 if (!$SVN_URL && !$url) {
127 croak "SVN repository location required: $url\n";
130 $repo_uuid = setup_git_svn();
133 if ($uuid ne $repo_uuid) {
134 croak "Repository UUIDs do not match!\ngot: $uuid\n",
135 "expected: $repo_uuid\n";
137 assert_revision_eq_or_unknown($rev, $c);
138 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
139 $newest_rev = $rev if ($rev > $newest_rev);
141 close $rev_list or croak $?;
142 if (!chdir $SVN_WC) {
143 my @svn_co = ('svn','co',"-r$first");
144 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
145 sys(@svn_co, $SVN_URL, $SVN_WC);
146 chdir $SVN_WC or croak $!;
150 defined $pid or croak $!;
152 my @svn_up = qw(svn up);
153 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
154 sys(@svn_up,"-r$newest_rev");
155 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
157 exec('git-write-tree');
163 $SVN_URL = shift or croak "SVN repository location required\n";
164 unless (-d $GIT_DIR) {
172 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
173 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
174 unless ($_revision) {
175 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
177 push @log_args, "-r$_revision";
178 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
180 my $svn_log = svn_log_raw(@log_args);
181 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
183 my $base = shift @$svn_log or croak "No base revision!\n";
184 my $last_commit = undef;
185 unless (-d $SVN_WC) {
186 my @svn_co = ('svn','co',"-r$base->{revision}");
187 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
188 sys(@svn_co, $SVN_URL, $SVN_WC);
189 chdir $SVN_WC or croak $!;
190 $last_commit = git_commit($base, @parents);
191 unless (-f "$GIT_DIR/refs/heads/master") {
192 sys(qw(git-update-ref refs/heads/master),$last_commit);
194 assert_svn_wc_clean($base->{revision}, $last_commit);
196 chdir $SVN_WC or croak $!;
197 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
199 my @svn_up = qw(svn up);
200 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
201 my $last_rev = $base->{revision};
202 foreach my $log_msg (@$svn_log) {
203 assert_svn_wc_clean($last_rev, $last_commit);
204 $last_rev = $log_msg->{revision};
205 sys(@svn_up,"-r$last_rev");
206 $last_commit = git_commit($log_msg, $last_commit, @parents);
208 assert_svn_wc_clean($last_rev, $last_commit);
209 return pop @$svn_log;
214 if ($_stdin || !@commits) {
215 print "Reading from stdin...\n";
218 if (/\b([a-f\d]{6,40})\b/) {
219 unshift @commits, $1;
224 foreach my $c (@commits) {
225 chomp(my @tmp = safe_qx('git-rev-parse',$c));
226 if (scalar @tmp == 1) {
228 } elsif (scalar @tmp > 1) {
229 push @revs, reverse (safe_qx('git-rev-list',@tmp));
231 die "Failed to rev-parse $c\n";
237 chdir $SVN_WC or croak $!;
238 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
239 foreach my $c (@revs) {
240 print "Committing $c\n";
241 svn_checkout_tree($svn_current_rev, $c);
242 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
244 print "Done committing ",scalar @revs," revisions to SVN\n";
248 ########################### utility functions #########################
251 defined $SVN_URL or croak "SVN repository location required\n";
252 unless (-d $GIT_DIR) {
253 croak "GIT_DIR=$GIT_DIR does not exist!\n";
255 mkpath(["$GIT_DIR/$GIT_SVN"]);
256 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
258 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
259 my $uuid = svn_info($SVN_URL)->{'Repository UUID'} or
260 croak "Repository UUID unreadable\n";
261 s_to_file($uuid,"$GIT_DIR/$GIT_SVN/info/uuid");
263 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
264 print $fd '.svn',"\n";
265 close $fd or croak $!;
269 sub assert_svn_wc_clean {
270 my ($svn_rev, $commit) = @_;
271 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
272 croak "$commit is not a sha1!\n" unless ($commit =~ /^$sha1$/o);
273 my $svn_info = svn_info('.');
274 if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
275 croak "Expected r$svn_rev, got r",
276 $svn_info->{'Last Changed Rev'},"\n";
278 my @status = grep(!/^Performing status on external/,(`svn status`));
279 @status = grep(!/^\s*$/,@status);
280 if (scalar @status) {
281 print STDERR "Tree ($SVN_WC) is not clean:\n";
282 print STDERR $_ foreach @status;
285 my ($tree_a) = grep(/^tree $sha1$/o,`git-cat-file commit $commit`);
286 $tree_a =~ s/^tree //;
288 chomp(my $tree_b = `GIT_INDEX_FILE=$GIT_SVN_INDEX git-write-tree`);
289 if ($tree_a ne $tree_b) {
290 croak "$svn_rev != $commit, $tree_a != $tree_b\n";
294 sub parse_diff_tree {
300 chomp $_; # this gets rid of the trailing "\0"
302 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
303 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
304 push @mods, { mode_a => $1, mode_b => $2,
305 sha1_b => $3, chg => $4 };
306 if ($4 =~ /^(?:C|R)$/) {
311 } elsif ($state eq 'file_a') {
312 my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
313 if ($x->{chg} !~ /^(?:C|R)$/) {
314 croak __LINE__,": Error parsing $_, $x->{chg}\n";
318 } elsif ($state eq 'file_b') {
319 my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
320 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
321 croak __LINE__,": Error parsing $_, $x->{chg}\n";
323 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
324 croak __LINE__,": Error parsing $_, $x->{chg}\n";
329 croak __LINE__,": Error parsing $_\n";
332 close $diff_fh or croak $!;
336 sub svn_check_prop_executable {
338 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
339 sys(qw(svn propset svn:executable 1), $m->{file_b});
340 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
341 sys(qw(svn propdel svn:executable), $m->{file_b});
345 sub svn_ensure_parent_path {
346 my $dir_b = dirname(shift);
347 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
348 mkpath([$dir_b]) unless (-d $dir_b);
349 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
352 sub svn_checkout_tree {
353 my ($svn_rev, $commit) = @_;
354 my $from = file_to_s("$REV_DIR/$svn_rev");
355 assert_svn_wc_clean($svn_rev,$from);
356 print "diff-tree '$from' '$commit'\n";
357 my $pid = open my $diff_fh, '-|';
358 defined $pid or croak $!;
360 my @diff_tree = qw(git-diff-tree -z -r -C);
361 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
362 push @diff_tree, "-l$_l" if defined $_l;
363 exec(@diff_tree, $from, $commit) or croak $!;
365 my $mods = parse_diff_tree($diff_fh);
367 # git can do empty commits, SVN doesn't allow it...
371 foreach my $m (@$mods) {
372 if ($m->{chg} eq 'C') {
373 svn_ensure_parent_path( $m->{file_b} );
374 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
375 blob_to_file( $m->{sha1_b}, $m->{file_b});
376 svn_check_prop_executable($m);
377 } elsif ($m->{chg} eq 'D') {
378 $rm{dirname $m->{file_b}}->{basename $m->{file_b}} = 1;
379 sys(qw(svn rm --force), $m->{file_b});
380 } elsif ($m->{chg} eq 'R') {
381 svn_ensure_parent_path( $m->{file_b} );
382 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
383 blob_to_file( $m->{sha1_b}, $m->{file_b});
384 svn_check_prop_executable($m);
385 $rm{dirname $m->{file_a}}->{basename $m->{file_a}} = 1;
386 } elsif ($m->{chg} eq 'M') {
387 if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^120/) {
388 unlink $m->{file_b} or croak $!;
389 blob_to_symlink($m->{sha1_b}, $m->{file_b});
391 blob_to_file($m->{sha1_b}, $m->{file_b});
393 svn_check_prop_executable($m);
394 } elsif ($m->{chg} eq 'T') {
395 sys(qw(svn rm --force),$m->{file_b});
396 if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^100/) {
397 blob_to_symlink($m->{sha1_b}, $m->{file_b});
399 blob_to_file($m->{sha1_b}, $m->{file_b});
401 svn_check_prop_executable($m);
402 sys(qw(svn add --force), $m->{file_b});
403 } elsif ($m->{chg} eq 'A') {
404 svn_ensure_parent_path( $m->{file_b} );
405 blob_to_file( $m->{sha1_b}, $m->{file_b});
406 if ($m->{mode_b} =~ /755$/) {
407 chmod 0755, $m->{file_b};
409 sys(qw(svn add --force), $m->{file_b});
411 croak "Invalid chg: $m->{chg}\n";
415 my $old_index = $ENV{GIT_INDEX_FILE};
416 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
417 foreach my $dir (keys %rm) {
418 my $files = $rm{$dir};
420 foreach (safe_qx('svn','ls',$dir)) {
422 push @files, $_ unless $files->{$_};
424 sys(qw(svn rm),$dir) unless @files;
427 $ENV{GIT_INDEX_FILE} = $old_index;
429 delete $ENV{GIT_INDEX_FILE};
434 sub svn_commit_tree {
435 my ($svn_rev, $commit) = @_;
436 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
437 open my $msg, '>', $commit_msg or croak $!;
439 chomp(my $type = `git-cat-file -t $commit`);
440 if ($type eq 'commit') {
441 my $pid = open my $msg_fh, '-|';
442 defined $pid or croak $!;
445 exec(qw(git-cat-file commit), $commit) or croak $!;
450 $in_msg = 1 if (/^\s*$/);
452 print $msg $_ or croak $!;
455 close $msg_fh or croak $!;
457 close $msg or croak $!;
459 if ($_edit || ($type eq 'tree')) {
460 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
461 system($editor, $commit_msg);
463 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
464 my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
466 defined $committed or croak
467 "Commit output failed to parse committed revision!\n",
468 join("\n",@ci_output),"\n";
469 my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
472 my @svn_up = (qw(svn up), "-r$svn_rev");
473 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
475 return fetch("$rev_committed=$commit")->{revision};
480 my $pid = open my $log_fh,'-|';
481 defined $pid or croak $!;
484 exec (qw(svn log), @log_args) or croak $!
492 if ($state eq 'msg') {
493 if ($svn_log[$#svn_log]->{lines}) {
494 $svn_log[$#svn_log]->{msg} .= $_."\n";
495 unless(--$svn_log[$#svn_log]->{lines}) {
499 croak "Log parse error at: $_\n",
500 $svn_log[$#svn_log]->{revision},
505 if ($state ne 'sep') {
506 croak "Log parse error at: $_\n",
508 $svn_log[$#svn_log]->{revision},
513 # if we have an empty log message, put something there:
515 $svn_log[$#svn_log]->{msg} ||= "\n";
516 delete $svn_log[$#svn_log]->{lines};
520 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
522 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
523 ($lines) = ($lines =~ /(\d+)/);
524 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
525 /(\d{4})\-(\d\d)\-(\d\d)\s
526 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
527 or croak "Failed to parse date: $date\n";
528 my %log_msg = ( revision => $rev,
529 date => "$tz $Y-$m-$d $H:$M:$S",
533 push @svn_log, \%log_msg;
534 $state = 'msg_start';
537 # skip the first blank line of the message:
538 if ($state eq 'msg_start' && /^$/) {
540 } elsif ($state eq 'msg') {
541 if ($svn_log[$#svn_log]->{lines}) {
542 $svn_log[$#svn_log]->{msg} .= $_."\n";
543 unless (--$svn_log[$#svn_log]->{lines}) {
547 croak "Log parse error at: $_\n",
548 $svn_log[$#svn_log]->{revision},"\n";
552 close $log_fh or croak $?;
557 my $url = shift || $SVN_URL;
559 my $pid = open my $info_fh, '-|';
560 defined $pid or croak $!;
563 exec(qw(svn info),$url) or croak $!;
567 # only single-lines seem to exist in svn info output
570 if (m#^([^:]+)\s*:\s*(\S*)$#) {
572 push @{$ret->{-order}}, $1;
575 close $info_fh or croak $!;
579 sub sys { system(@_) == 0 or croak $? }
582 system( "git-diff-files --name-only -z ".
583 " | git-update-index --remove -z --stdin && ".
584 "git-ls-files -z --others ".
585 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
586 " | git-update-index --add -z --stdin"
591 my ($str, $file, $mode) = @_;
592 open my $fd,'>',$file or croak $!;
593 print $fd $str,"\n" or croak $!;
594 close $fd or croak $!;
595 chmod ($mode &~ umask, $file) if (defined $mode);
600 open my $fd,'<',$file or croak "$!: file: $file\n";
603 close $fd or croak $!;
608 sub assert_revision_unknown {
610 if (-f "$REV_DIR/$revno") {
611 croak "$REV_DIR/$revno already exists! ",
612 "Why are we refetching it?";
616 sub assert_revision_eq_or_unknown {
617 my ($revno, $commit) = @_;
618 if (-f "$REV_DIR/$revno") {
619 my $current = file_to_s("$REV_DIR/$revno");
620 if ($commit ne $current) {
621 croak "$REV_DIR/$revno already exists!\n",
622 "current: $current\nexpected: $commit\n";
629 my ($log_msg, @parents) = @_;
630 assert_revision_unknown($log_msg->{revision});
631 my $out_fh = IO::File->new_tmpfile or croak $!;
632 my $info = svn_info('.');
633 my $uuid = $info->{'Repository UUID'};
634 defined $uuid or croak "Unable to get Repository UUID\n";
636 # commit parents can be conditionally bound to a particular
637 # svn revision via: "svn_revno=commit_sha1", filter them out here:
639 foreach my $p (@parents) {
640 next unless defined $p;
641 if ($p =~ /^(\d+)=($sha1_short)$/o) {
642 if ($1 == $log_msg->{revision}) {
643 push @exec_parents, $2;
646 push @exec_parents, $p if $p =~ /$sha1_short/o;
651 defined $pid or croak $!;
653 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
655 chomp(my $tree = `git-write-tree`);
657 my $msg_fh = IO::File->new_tmpfile or croak $!;
658 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
659 "$SVN_URL\@$log_msg->{revision}",
660 " $uuid\n" or croak $!;
661 $msg_fh->flush == 0 or croak $!;
662 seek $msg_fh, 0, 0 or croak $!;
664 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} =
666 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
667 $log_msg->{author}."\@$uuid";
668 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} =
670 my @exec = ('git-commit-tree',$tree);
671 push @exec, '-p', $_ foreach @exec_parents;
672 open STDIN, '<&', $msg_fh or croak $!;
673 open STDOUT, '>&', $out_fh or croak $!;
674 exec @exec or croak $!;
679 $out_fh->flush == 0 or croak $!;
680 seek $out_fh, 0, 0 or croak $!;
681 chomp(my $commit = do { local $/; <$out_fh> });
682 if ($commit !~ /^$sha1$/o) {
683 croak "Failed to commit, invalid sha1: $commit\n";
685 my @update_ref = ('git-update-ref',"refs/heads/$GIT_SVN-HEAD",$commit);
686 if (my $primary_parent = shift @exec_parents) {
687 push @update_ref, $primary_parent;
690 sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
691 print "r$log_msg->{revision} = $commit\n";
695 sub blob_to_symlink {
696 my ($blob, $link) = @_;
697 defined $link or croak "\$link not defined!\n";
698 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
699 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
700 symlink $dest, $link or croak $!;
704 my ($blob, $file) = @_;
705 defined $file or croak "\$file not defined!\n";
706 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
707 open my $blob_fh, '>', $file or croak "$!: $file\n";
709 defined $pid or croak $!;
712 open STDOUT, '>&', $blob_fh or croak $!;
713 exec('git-cat-file','blob',$blob);
718 close $blob_fh or croak $!;
722 my $pid = open my $child, '-|';
723 defined $pid or croak $!;
725 exec(@_) or croak $?;
727 my @ret = (<$child>);
728 close $child or croak $?;
729 die $? if $?; # just in case close didn't error out
730 return wantarray ? @ret : join('',@ret);
733 sub svn_check_ignore_externals {
734 return if $_no_ignore_ext;
735 unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
736 print STDERR "W: Installed svn version does not support ",
737 "--ignore-externals\n";
745 @svn_log = array of log_msg hashes
749 msg => 'whitespace-formatted log entry
750 ', # trailing newline is preserved
751 revision => '8', # integer
752 date => '2004-02-24T17:01:44.108345Z', # commit date
753 author => 'committer name'
757 @mods = array of diff-index line hashes, each element represents one line
760 diff-index line ($m hash)
762 mode_a => first column of diff-index output, no leading ':',
763 mode_b => second column of diff-index output,
764 sha1_b => sha1sum of the final blob,
765 chg => change type [MCRAD],
766 file_a => original file name of a file (iff chg is 'C' or 'R')
767 file_b => new/current file name of a file (any chg)