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 # See what I do with XML::Simple to make the dependency optional.
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);
35 GetOptions( 'revision|r=s' => \$_revision,
36 'no-ignore-externals' => \$_no_ignore_ext,
40 'help|H|h' => \$_help,
41 'no-stop-copy' => \$_no_stop_copy );
43 fetch => [ \&fetch, "Download new revisions from SVN" ],
44 init => [ \&init, "Initialize and fetch (import)"],
45 commit => [ \&commit, "Commit git revisions to SVN" ],
46 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)" ],
47 help => [ \&usage, "Show help" ],
50 for (my $i = 0; $i < @ARGV; $i++) {
51 if (defined $cmd{$ARGV[$i]}) {
58 # we may be called as git-svn-(command), or git-svn(command).
60 if (/git\-svn\-?($_)(?:\.\w+)?$/) {
66 usage(1) unless (defined $cmd);
67 svn_check_ignore_externals();
68 $cmd{$cmd}->[0]->(@ARGV);
71 ####################### primary functions ######################
73 my $exit = shift || 0;
74 my $fd = $exit ? \*STDERR : \*STDOUT;
76 git-svn - bidirectional operations between a single Subversion tree and git
77 Usage: $0 <command> [options] [arguments]\n
80 foreach (sort keys %cmd) {
81 print $fd ' ',pack('A10',$_),$cmd{$_}->[1],"\n";
84 \nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
85 you're tracking multiple SVN branches/repositories in one git repository
86 and want to keep them separate.
92 $SVN_URL = shift or undef;
96 my $pid = open(my $rev_list,'-|');
97 defined $pid or croak $!;
99 exec("git-rev-list","$GIT_SVN-HEAD") or croak $!;
102 while (<$rev_list>) {
105 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
106 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
107 next if (!@commit); # skip merges
108 my $id = $commit[$#commit];
109 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
111 if (!$rev || !$uuid || !$url) {
112 # some of the original repositories I made had
113 # indentifiers like this:
114 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
116 if (!$rev || !$uuid) {
117 croak "Unable to extract revision or UUID from ",
121 print "r$rev = $c\n";
122 unless (defined $first) {
123 if (!$SVN_URL && !$url) {
124 croak "SVN repository location required: $url\n";
127 $repo_uuid = setup_git_svn();
130 if ($uuid ne $repo_uuid) {
131 croak "Repository UUIDs do not match!\ngot: $uuid\n",
132 "expected: $repo_uuid\n";
134 assert_revision_eq_or_unknown($rev, $c);
135 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
136 $newest_rev = $rev if ($rev > $newest_rev);
138 close $rev_list or croak $?;
139 if (!chdir $SVN_WC) {
140 my @svn_co = ('svn','co',"-r$first");
141 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
142 sys(@svn_co, $SVN_URL, $SVN_WC);
143 chdir $SVN_WC or croak $!;
147 defined $pid or croak $!;
149 my @svn_up = qw(svn up);
150 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
151 sys(@svn_up,"-r$newest_rev");
152 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
154 exec('git-write-tree');
160 $SVN_URL = shift or croak "SVN repository location required\n";
161 unless (-d $GIT_DIR) {
169 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
170 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
171 unless ($_revision) {
172 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
174 push @log_args, "-r$_revision";
175 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
177 eval { require XML::Simple or croak $! };
178 my $svn_log = $@ ? svn_log_raw(@log_args) : svn_log_xml(@log_args);
179 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
181 my $base = shift @$svn_log or croak "No base revision!\n";
182 my $last_commit = undef;
183 unless (-d $SVN_WC) {
184 my @svn_co = ('svn','co',"-r$base->{revision}");
185 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
186 sys(@svn_co, $SVN_URL, $SVN_WC);
187 chdir $SVN_WC or croak $!;
188 $last_commit = git_commit($base, @parents);
189 unless (-f "$GIT_DIR/refs/heads/master") {
190 sys(qw(git-update-ref refs/heads/master),$last_commit);
192 assert_svn_wc_clean($base->{revision}, $last_commit);
194 chdir $SVN_WC or croak $!;
195 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
197 my @svn_up = qw(svn up);
198 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
199 my $last_rev = $base->{revision};
200 foreach my $log_msg (@$svn_log) {
201 assert_svn_wc_clean($last_rev, $last_commit);
202 $last_rev = $log_msg->{revision};
203 sys(@svn_up,"-r$last_rev");
204 $last_commit = git_commit($log_msg, $last_commit, @parents);
206 assert_svn_wc_clean($last_rev, $last_commit);
207 return pop @$svn_log;
212 if ($_stdin || !@commits) {
213 print "Reading from stdin...\n";
216 if (/^([a-f\d]{6,40})\b/) {
217 unshift @commits, $1;
223 push @revs, (safe_qx('git-rev-parse',$_));
228 chdir $SVN_WC or croak $!;
229 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
230 foreach my $c (@revs) {
231 print "Committing $c\n";
232 svn_checkout_tree($svn_current_rev, $c);
233 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
235 print "Done committing ",scalar @revs," revisions to SVN\n";
239 ########################### utility functions #########################
242 defined $SVN_URL or croak "SVN repository location required\n";
243 unless (-d $GIT_DIR) {
244 croak "GIT_DIR=$GIT_DIR does not exist!\n";
246 mkpath(["$GIT_DIR/$GIT_SVN"]);
247 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
249 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
250 my $uuid = svn_info($SVN_URL)->{'Repository UUID'} or
251 croak "Repository UUID unreadable\n";
252 s_to_file($uuid,"$GIT_DIR/$GIT_SVN/info/uuid");
254 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
255 print $fd '.svn',"\n";
256 close $fd or croak $!;
260 sub assert_svn_wc_clean {
261 my ($svn_rev, $commit) = @_;
262 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
263 croak "$commit is not a sha1!\n" unless ($commit =~ /^$sha1$/o);
264 my $svn_info = svn_info('.');
265 if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
266 croak "Expected r$svn_rev, got r",
267 $svn_info->{'Last Changed Rev'},"\n";
269 my @status = grep(!/^Performing status on external/,(`svn status`));
270 @status = grep(!/^\s*$/,@status);
271 if (scalar @status) {
272 print STDERR "Tree ($SVN_WC) is not clean:\n";
273 print STDERR $_ foreach @status;
276 my ($tree_a) = grep(/^tree $sha1$/o,`git-cat-file commit $commit`);
277 $tree_a =~ s/^tree //;
279 chomp(my $tree_b = `GIT_INDEX_FILE=$GIT_SVN_INDEX git-write-tree`);
280 if ($tree_a ne $tree_b) {
281 croak "$svn_rev != $commit, $tree_a != $tree_b\n";
285 sub parse_diff_tree {
291 chomp $_; # this gets rid of the trailing "\0"
293 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
294 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
295 push @mods, { mode_a => $1, mode_b => $2,
296 sha1_b => $3, chg => $4 };
297 if ($4 =~ /^(?:C|R)$/) {
302 } elsif ($state eq 'file_a') {
303 my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
304 if ($x->{chg} !~ /^(?:C|R)$/) {
305 croak __LINE__,": Error parsing $_, $x->{chg}\n";
309 } elsif ($state eq 'file_b') {
310 my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
311 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
312 croak __LINE__,": Error parsing $_, $x->{chg}\n";
314 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
315 croak __LINE__,": Error parsing $_, $x->{chg}\n";
320 croak __LINE__,": Error parsing $_\n";
323 close $diff_fh or croak $!;
327 sub svn_check_prop_executable {
329 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
330 sys(qw(svn propset svn:executable 1), $m->{file_b});
331 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
332 sys(qw(svn propdel svn:executable), $m->{file_b});
336 sub svn_ensure_parent_path {
337 my $dir_b = dirname(shift);
338 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
339 mkpath([$dir_b]) unless (-d $dir_b);
340 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
343 sub svn_checkout_tree {
344 my ($svn_rev, $commit) = @_;
345 my $from = file_to_s("$REV_DIR/$svn_rev");
346 assert_svn_wc_clean($svn_rev,$from);
347 print "diff-tree '$from' '$commit'\n";
348 my $pid = open my $diff_fh, '-|';
349 defined $pid or croak $!;
351 exec(qw(git-diff-tree -z -r -C), $from, $commit) or croak $!;
353 my $mods = parse_diff_tree($diff_fh);
355 # git can do empty commits, SVN doesn't allow it...
359 foreach my $m (@$mods) {
360 if ($m->{chg} eq 'C') {
361 svn_ensure_parent_path( $m->{file_b} );
362 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
363 blob_to_file( $m->{sha1_b}, $m->{file_b});
364 svn_check_prop_executable($m);
365 } elsif ($m->{chg} eq 'D') {
366 $rm{dirname $m->{file_b}}->{basename $m->{file_b}} = 1;
367 sys(qw(svn rm --force), $m->{file_b});
368 } elsif ($m->{chg} eq 'R') {
369 svn_ensure_parent_path( $m->{file_b} );
370 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
371 blob_to_file( $m->{sha1_b}, $m->{file_b});
372 svn_check_prop_executable($m);
373 $rm{dirname $m->{file_a}}->{basename $m->{file_a}} = 1;
374 } elsif ($m->{chg} eq 'M') {
375 if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^120/) {
376 unlink $m->{file_b} or croak $!;
377 blob_to_symlink($m->{sha1_b}, $m->{file_b});
379 blob_to_file($m->{sha1_b}, $m->{file_b});
381 svn_check_prop_executable($m);
382 } elsif ($m->{chg} eq 'T') {
383 sys(qw(svn rm --force),$m->{file_b});
384 if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^100/) {
385 blob_to_symlink($m->{sha1_b}, $m->{file_b});
387 blob_to_file($m->{sha1_b}, $m->{file_b});
389 svn_check_prop_executable($m);
390 sys(qw(svn add --force), $m->{file_b});
391 } elsif ($m->{chg} eq 'A') {
392 svn_ensure_parent_path( $m->{file_b} );
393 blob_to_file( $m->{sha1_b}, $m->{file_b});
394 if ($m->{mode_b} =~ /755$/) {
395 chmod 0755, $m->{file_b};
397 sys(qw(svn add --force), $m->{file_b});
399 croak "Invalid chg: $m->{chg}\n";
403 my $old_index = $ENV{GIT_INDEX_FILE};
404 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
405 foreach my $dir (keys %rm) {
406 my $files = $rm{$dir};
408 foreach (safe_qx('svn','ls',$dir)) {
410 push @files, $_ unless $files->{$_};
412 sys(qw(svn rm),$dir) unless @files;
415 $ENV{GIT_INDEX_FILE} = $old_index;
417 delete $ENV{GIT_INDEX_FILE};
422 sub svn_commit_tree {
423 my ($svn_rev, $commit) = @_;
424 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
425 open my $msg, '>', $commit_msg or croak $!;
427 chomp(my $type = `git-cat-file -t $commit`);
428 if ($type eq 'commit') {
429 my $pid = open my $msg_fh, '-|';
430 defined $pid or croak $!;
433 exec(qw(git-cat-file commit), $commit) or croak $!;
438 $in_msg = 1 if (/^\s*$/);
440 print $msg $_ or croak $!;
443 close $msg_fh or croak $!;
445 close $msg or croak $!;
447 if ($_edit || ($type eq 'tree')) {
448 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
449 system($editor, $commit_msg);
451 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
452 my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
454 defined $committed or croak
455 "Commit output failed to parse committed revision!\n",
456 join("\n",@ci_output),"\n";
457 my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
460 my @svn_up = (qw(svn up), "-r$svn_rev");
461 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
463 return fetch("$rev_committed=$commit")->{revision};
468 my $log_fh = IO::File->new_tmpfile or croak $!;
471 defined $pid or croak $!;
474 open STDOUT, '>&', $log_fh or croak $!;
475 exec (qw(svn log --xml), @log_args) or croak $!
483 my $log = XML::Simple::XMLin( $log_fh,
484 ForceArray => ['path','revision','logentry'],
486 KeyAttr => { logentry => '+revision',
489 foreach my $r (sort {$a <=> $b} keys %$log) {
490 my $log_msg = $log->{$r};
491 my ($Y,$m,$d,$H,$M,$S) = ($log_msg->{date} =~
492 /(\d{4})\-(\d\d)\-(\d\d)T
493 (\d\d)\:(\d\d)\:(\d\d)\.\d+Z$/x)
494 or croak "Failed to parse date: ",
496 $log_msg->{date} = "+0000 $Y-$m-$d $H:$M:$S";
498 # XML::Simple can't handle <msg></msg> as a string:
499 if (ref $log_msg->{msg} eq 'HASH') {
500 $log_msg->{msg} = "\n";
502 $log_msg->{msg} .= "\n";
504 push @svn_log, $log->{$r};
511 my $pid = open my $log_fh,'-|';
512 defined $pid or croak $!;
515 exec (qw(svn log), @log_args) or croak $!
525 # if we have an empty log message, put something there:
527 $svn_log[$#svn_log]->{msg} ||= "\n";
531 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
533 my ($author, $date) = split(/\s*\|\s*/, $_, 2);
534 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
535 /(\d{4})\-(\d\d)\-(\d\d)\s
536 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
537 or croak "Failed to parse date: $date\n";
538 my %log_msg = ( revision => $rev,
539 date => "$tz $Y-$m-$d $H:$M:$S",
542 push @svn_log, \%log_msg;
543 $state = 'msg_start';
546 # skip the first blank line of the message:
547 if ($state eq 'msg_start' && /^$/) {
549 } elsif ($state eq 'msg') {
550 $svn_log[$#svn_log]->{msg} .= $_."\n";
553 close $log_fh or croak $?;
558 my $url = shift || $SVN_URL;
560 my $pid = open my $info_fh, '-|';
561 defined $pid or croak $!;
564 exec(qw(svn info),$url) or croak $!;
568 # only single-lines seem to exist in svn info output
571 if (m#^([^:]+)\s*:\s*(\S*)$#) {
573 push @{$ret->{-order}}, $1;
576 close $info_fh or croak $!;
580 sub sys { system(@_) == 0 or croak $? }
583 system( "git-ls-files -z --others ".
584 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
585 "| git-update-index --add -z --stdin; ".
586 "git-ls-files -z --deleted ".
587 "| git-update-index --remove -z --stdin; ".
588 "git-ls-files -z --modified".
589 "| git-update-index -z --stdin") == 0 or croak $?
593 my ($str, $file, $mode) = @_;
594 open my $fd,'>',$file or croak $!;
595 print $fd $str,"\n" or croak $!;
596 close $fd or croak $!;
597 chmod ($mode &~ umask, $file) if (defined $mode);
602 open my $fd,'<',$file or croak "$!: file: $file\n";
605 close $fd or croak $!;
610 sub assert_revision_unknown {
612 if (-f "$REV_DIR/$revno") {
613 croak "$REV_DIR/$revno already exists! ",
614 "Why are we refetching it?";
618 sub assert_revision_eq_or_unknown {
619 my ($revno, $commit) = @_;
620 if (-f "$REV_DIR/$revno") {
621 my $current = file_to_s("$REV_DIR/$revno");
622 if ($commit ne $current) {
623 croak "$REV_DIR/$revno already exists!\n",
624 "current: $current\nexpected: $commit\n";
631 my ($log_msg, @parents) = @_;
632 assert_revision_unknown($log_msg->{revision});
633 my $out_fh = IO::File->new_tmpfile or croak $!;
634 my $info = svn_info('.');
635 my $uuid = $info->{'Repository UUID'};
636 defined $uuid or croak "Unable to get Repository UUID\n";
638 # commit parents can be conditionally bound to a particular
639 # svn revision via: "svn_revno=commit_sha1", filter them out here:
641 foreach my $p (@parents) {
642 next unless defined $p;
643 if ($p =~ /^(\d+)=($sha1_short)$/o) {
644 if ($1 == $log_msg->{revision}) {
645 push @exec_parents, $2;
648 push @exec_parents, $p if $p =~ /$sha1_short/o;
653 defined $pid or croak $!;
655 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
657 chomp(my $tree = `git-write-tree`);
659 my $msg_fh = IO::File->new_tmpfile or croak $!;
660 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
661 "$SVN_URL\@$log_msg->{revision}",
662 " $uuid\n" or croak $!;
663 $msg_fh->flush == 0 or croak $!;
664 seek $msg_fh, 0, 0 or croak $!;
666 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} =
668 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
669 $log_msg->{author}."\@$uuid";
670 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} =
672 my @exec = ('git-commit-tree',$tree);
673 push @exec, '-p', $_ foreach @exec_parents;
674 open STDIN, '<&', $msg_fh or croak $!;
675 open STDOUT, '>&', $out_fh or croak $!;
676 exec @exec or croak $!;
681 $out_fh->flush == 0 or croak $!;
682 seek $out_fh, 0, 0 or croak $!;
683 chomp(my $commit = do { local $/; <$out_fh> });
684 if ($commit !~ /^$sha1$/o) {
685 croak "Failed to commit, invalid sha1: $commit\n";
687 my @update_ref = ('git-update-ref',"refs/heads/$GIT_SVN-HEAD",$commit);
688 if (my $primary_parent = shift @exec_parents) {
689 push @update_ref, $primary_parent;
692 sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
693 print "r$log_msg->{revision} = $commit\n";
697 sub blob_to_symlink {
698 my ($blob, $link) = @_;
699 defined $link or croak "\$link not defined!\n";
700 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
701 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
702 symlink $dest, $link or croak $!;
706 my ($blob, $file) = @_;
707 defined $file or croak "\$file not defined!\n";
708 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
709 open my $blob_fh, '>', $file or croak "$!: $file\n";
711 defined $pid or croak $!;
714 open STDOUT, '>&', $blob_fh or croak $!;
715 exec('git-cat-file','blob',$blob);
720 close $blob_fh or croak $!;
724 my $pid = open my $child, '-|';
725 defined $pid or croak $!;
727 exec(@_) or croak $?;
729 my @ret = (<$child>);
730 close $child or croak $?;
731 die $? if $?; # just in case close didn't error out
732 return wantarray ? @ret : join('',@ret);
735 sub svn_check_ignore_externals {
736 return if $_no_ignore_ext;
737 unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
738 print STDERR "W: Installed svn version does not support ",
739 "--ignore-externals\n";
747 @svn_log = array of log_msg hashes
751 msg => 'whitespace-formatted log entry
752 ', # trailing newline is preserved
753 revision => '8', # integer
754 date => '2004-02-24T17:01:44.108345Z', # commit date
755 author => 'committer name'
759 @mods = array of diff-index line hashes, each element represents one line
762 diff-index line ($m hash)
764 mode_a => first column of diff-index output, no leading ':',
765 mode_b => second column of diff-index output,
766 sha1_b => sha1sum of the final blob,
767 chg => change type [MCRAD],
768 file_a => original file name of a file (iff chg is 'C' or 'R')
769 file_b => new/current file name of a file (any chg)