2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $REV_DIR $GIT_SVN_DIR/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '1.1.0-pre';
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
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
25 # We don't use any modules not in the standard Perl distribution:
28 use File::Basename qw/dirname basename/;
29 use File::Path qw/mkpath/;
30 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
32 use POSIX qw/strftime/;
33 my $sha1 = qr/[a-f\d]{40}/;
34 my $sha1_short = qr/[a-f\d]{4,40}/;
35 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
36 $_find_copies_harder, $_l, $_cp_similarity,
37 $_repack, $_repack_nr, $_repack_flags,
38 $_version, $_upgrade, $_authors, $_branch_all_refs);
39 my (@_branch_from, %tree_map, %users);
40 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
41 my @repo_path_split_cache;
43 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
44 'branch|b=s' => \@_branch_from,
45 'branch-all-refs|B' => \$_branch_all_refs,
46 'authors-file|A=s' => \$_authors,
47 'repack:i' => \$_repack,
48 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
50 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
51 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
54 fetch => [ \&fetch, "Download new revisions from SVN",
55 { 'revision|r=s' => \$_revision, %fc_opts } ],
56 init => [ \&init, "Initialize a repo for tracking" .
57 " (requires URL argument)", { } ],
58 commit => [ \&commit, "Commit git revisions to SVN",
59 { 'stdin|' => \$_stdin,
62 'find-copies-harder' => \$_find_copies_harder,
64 'copy-similarity|C=i'=> \$_cp_similarity,
67 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
68 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
69 { 'no-ignore-externals' => \$_no_ignore_ext,
70 'upgrade' => \$_upgrade } ],
73 for (my $i = 0; $i < @ARGV; $i++) {
74 if (defined $cmd{$ARGV[$i]}) {
81 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
83 read_repo_config(\%opts);
84 GetOptions(%opts, 'help|H|h' => \$_help,
85 'version|V' => \$_version,
86 'id|i=s' => \$GIT_SVN) or exit 1;
90 version() if $_version;
91 usage(1) unless defined $cmd;
93 load_authors() if $_authors;
94 load_all_refs() if $_branch_all_refs;
96 migration_check() unless $cmd eq 'init';
97 $cmd{$cmd}->[0]->(@ARGV);
100 ####################### primary functions ######################
102 my $exit = shift || 0;
103 my $fd = $exit ? \*STDERR : \*STDOUT;
105 git-svn - bidirectional operations between a single Subversion tree and git
106 Usage: $0 <command> [options] [arguments]\n
108 print $fd "Available commands:\n" unless $cmd;
110 foreach (sort keys %cmd) {
111 next if $cmd && $cmd ne $_;
112 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
113 foreach (keys %{$cmd{$_}->[2]}) {
114 # prints out arguments as they should be passed:
115 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
116 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
118 split /\|/,$_)," $x\n";
122 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
123 arbitrary identifier if you're tracking multiple SVN branches/repositories in
124 one git repository and want to keep them separate. See git-svn(1) for more
131 print "git-svn version $VERSION\n";
136 $SVN_URL = shift or undef;
139 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
141 check_upgrade_needed();
144 my $pid = open(my $rev_list,'-|');
145 defined $pid or croak $!;
147 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
150 while (<$rev_list>) {
153 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
154 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
155 next if (!@commit); # skip merges
156 my $id = $commit[$#commit];
157 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
159 if (!$rev || !$uuid || !$url) {
160 # some of the original repositories I made had
161 # indentifiers like this:
162 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
164 if (!$rev || !$uuid) {
165 croak "Unable to extract revision or UUID from ",
170 # if we merged or otherwise started elsewhere, this is
171 # how we break out of it
172 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
173 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
175 print "r$rev = $c\n";
176 unless (defined $latest) {
177 if (!$SVN_URL && !$url) {
178 croak "SVN repository location required: $url\n";
185 assert_revision_eq_or_unknown($rev, $c);
186 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
187 $newest_rev = $rev if ($rev > $newest_rev);
189 close $rev_list or croak $?;
190 if (!chdir $SVN_WC) {
191 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
192 chdir $SVN_WC or croak $!;
196 defined $pid or croak $!;
198 my @svn_up = qw(svn up);
199 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
200 sys(@svn_up,"-r$newest_rev");
201 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
203 exec('git-write-tree') or croak $!;
210 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
211 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
217 $SVN_URL = shift or die "SVN repository location required " .
218 "as a command-line argument\n";
219 unless (-d $GIT_DIR) {
227 check_upgrade_needed();
228 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
229 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
230 unless ($_revision) {
231 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
233 push @log_args, "-r$_revision";
234 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
236 my $svn_log = svn_log_raw(@log_args);
238 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
239 my $last_commit = undef;
240 unless (-d $SVN_WC) {
241 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
242 chdir $SVN_WC or croak $!;
244 $last_commit = git_commit($base, @parents);
245 assert_tree($last_commit);
247 chdir $SVN_WC or croak $!;
249 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
250 # looks like a user manually cp'd and svn switch'ed
251 unless ($last_commit) {
252 sys(qw/svn revert -R ./);
253 assert_svn_wc_clean($base->{revision});
254 $last_commit = git_commit($base, @parents);
255 assert_tree($last_commit);
258 my @svn_up = qw(svn up);
259 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
261 while (my $log_msg = next_log_entry($svn_log)) {
262 assert_tree($last_commit);
263 if ($last->{revision} >= $log_msg->{revision}) {
264 croak "Out of order: last >= current: ",
265 "$last->{revision} >= $log_msg->{revision}\n";
267 # Revert is needed for cases like:
268 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
269 # I can't seem to reproduce something like that on a test...
270 sys(qw/svn revert -R ./);
271 assert_svn_wc_clean($last->{revision});
272 sys(@svn_up,"-r$log_msg->{revision}");
273 $last_commit = git_commit($log_msg, $last_commit, @parents);
276 unless (-e "$GIT_DIR/refs/heads/master") {
277 sys(qw(git-update-ref refs/heads/master),$last_commit);
279 close $svn_log->{fh};
285 check_upgrade_needed();
286 if ($_stdin || !@commits) {
287 print "Reading from stdin...\n";
290 if (/\b($sha1_short)\b/o) {
291 unshift @commits, $1;
296 foreach my $c (@commits) {
297 chomp(my @tmp = safe_qx('git-rev-parse',$c));
298 if (scalar @tmp == 1) {
300 } elsif (scalar @tmp > 1) {
301 push @revs, reverse (safe_qx('git-rev-list',@tmp));
303 die "Failed to rev-parse $c\n";
308 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
309 my $info = svn_info('.');
310 my $fetched = fetch();
311 if ($info->{Revision} != $fetched->{revision}) {
312 print STDERR "There are new revisions that were fetched ",
313 "and need to be merged (or acknowledged) ",
314 "before committing.\n";
317 $info = svn_info('.');
319 my $svn_current_rev = $info->{'Last Changed Rev'};
320 foreach my $c (@revs) {
321 my $mods = svn_checkout_tree($svn_current_rev, $c);
322 if (scalar @$mods == 0) {
323 print "Skipping, no changes detected\n";
326 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
328 print "Done committing ",scalar @revs," revisions to SVN\n";
332 require File::Find or die $!;
333 my $exclude_file = "$GIT_DIR/info/exclude";
334 open my $fh, '<', $exclude_file or croak $!;
335 chomp(my @excludes = (<$fh>));
336 close $fh or croak $!;
338 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
339 chdir $SVN_WC or croak $!;
341 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
343 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
344 }}, no_chdir=>1},'.');
347 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
349 foreach my $i (sort keys %ign) {
350 print "\n# ",$i,"\n";
351 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
355 ########################### utility functions #########################
359 my $info = shift || svn_info('.');
360 $SVN_UUID = $info->{'Repository UUID'} or
361 croak "Repository UUID unreadable\n";
362 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
367 defined $pid or croak $!;
369 open my $null, '>', '/dev/null' or croak $!;
370 open STDERR, '>&', $null or croak $!;
371 open STDOUT, '>&', $null or croak $!;
378 sub repo_path_split {
379 my $full_url = shift;
380 $full_url =~ s#/+$##;
382 foreach (@repo_path_split_cache) {
383 if ($full_url =~ s#$_##) {
385 $full_url =~ s#^/+##;
386 return ($u, $full_url);
390 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
392 my @paths = split(m#/+#, $path);
394 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
395 my $n = shift @paths || last;
398 push @repo_path_split_cache, qr/^(\Q$url\E)/;
399 return ($url, $path);
403 defined $SVN_URL or croak "SVN repository location required\n";
404 unless (-d $GIT_DIR) {
405 croak "GIT_DIR=$GIT_DIR does not exist!\n";
407 mkpath([$GIT_SVN_DIR]);
408 mkpath(["$GIT_SVN_DIR/info"]);
410 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
412 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
413 print $fd '.svn',"\n";
414 close $fd or croak $!;
415 my ($url, $path) = repo_path_split($SVN_URL);
416 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
417 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
420 sub assert_svn_wc_clean {
422 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
423 my $lcr = svn_info('.')->{'Last Changed Rev'};
424 if ($svn_rev != $lcr) {
425 print STDERR "Checking for copy-tree ... ";
426 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
427 "-r$lcr:$svn_rev")));
429 croak "Nope! Expected r$svn_rev, got r$lcr\n";
431 print STDERR "OK!\n";
434 my @status = grep(!/^Performing status on external/,(`svn status`));
435 @status = grep(!/^\s*$/,@status);
436 if (scalar @status) {
437 print STDERR "Tree ($SVN_WC) is not clean:\n";
438 print STDERR $_ foreach @status;
445 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
446 chomp(my $type = `git-cat-file -t $treeish`);
448 while ($type eq 'tag') {
449 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
451 if ($type eq 'commit') {
452 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
453 ($expected) = ($expected =~ /^tree ($sha1)$/);
454 die "Unable to get tree from $treeish\n" unless $expected;
455 } elsif ($type eq 'tree') {
456 $expected = $treeish;
458 die "$treeish is a $type, expected tree, tag or commit\n";
461 my $old_index = $ENV{GIT_INDEX_FILE};
462 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
464 unlink $tmpindex or croak $!;
466 $ENV{GIT_INDEX_FILE} = $tmpindex;
468 chomp(my $tree = `git-write-tree`);
470 $ENV{GIT_INDEX_FILE} = $old_index;
472 delete $ENV{GIT_INDEX_FILE};
474 if ($tree ne $expected) {
475 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
480 sub parse_diff_tree {
486 chomp $_; # this gets rid of the trailing "\0"
487 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
488 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
489 push @mods, { mode_a => $1, mode_b => $2,
490 sha1_b => $3, chg => $4 };
491 if ($4 =~ /^(?:C|R)$/) {
496 } elsif ($state eq 'file_a') {
497 my $x = $mods[$#mods] or croak "Empty array\n";
498 if ($x->{chg} !~ /^(?:C|R)$/) {
499 croak "Error parsing $_, $x->{chg}\n";
503 } elsif ($state eq 'file_b') {
504 my $x = $mods[$#mods] or croak "Empty array\n";
505 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
506 croak "Error parsing $_, $x->{chg}\n";
508 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
509 croak "Error parsing $_, $x->{chg}\n";
514 croak "Error parsing $_\n";
517 close $diff_fh or croak $!;
522 sub svn_check_prop_executable {
524 return if -l $m->{file_b};
525 if ($m->{mode_b} =~ /755$/) {
526 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
527 if ($m->{mode_a} !~ /755$/) {
528 sys(qw(svn propset svn:executable 1), $m->{file_b});
530 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
531 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
532 sys(qw(svn propdel svn:executable), $m->{file_b});
533 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
534 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
538 sub svn_ensure_parent_path {
539 my $dir_b = dirname(shift);
540 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
541 mkpath([$dir_b]) unless (-d $dir_b);
542 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
545 sub precommit_check {
547 my (%rm_file, %rmdir_check, %added_check);
549 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
550 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
551 if ($m->{chg} eq 'R') {
552 if (-d $m->{file_b}) {
553 err_dir_to_file("$m->{file_a} => $m->{file_b}");
555 # dir/$file => dir/file/$file
556 my $dirname = dirname($m->{file_b});
557 while ($dirname ne File::Spec->curdir) {
558 if ($dirname ne $m->{file_a}) {
559 $dirname = dirname($dirname);
562 err_file_to_dir("$m->{file_a} => $m->{file_b}");
564 # baz/zzz => baz (baz is a file)
565 $dirname = dirname($m->{file_a});
566 while ($dirname ne File::Spec->curdir) {
567 if ($dirname ne $m->{file_b}) {
568 $dirname = dirname($dirname);
571 err_dir_to_file("$m->{file_a} => $m->{file_b}");
574 if ($m->{chg} =~ /^(D|R)$/) {
575 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
576 $rm_file{ $m->{$t} } = 1;
577 my $dirname = dirname( $m->{$t} );
578 my $basename = basename( $m->{$t} );
579 $rmdir_check{$dirname}->{$basename} = 1;
580 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
581 if (-d $m->{file_b}) {
582 err_dir_to_file($m->{file_b});
584 my $dirname = dirname( $m->{file_b} );
585 my $basename = basename( $m->{file_b} );
586 $added_check{$dirname}->{$basename} = 1;
587 while ($dirname ne File::Spec->curdir) {
588 if ($rm_file{$dirname}) {
589 err_file_to_dir($m->{file_b});
591 $dirname = dirname $dirname;
595 return (\%rmdir_check, \%added_check);
597 sub err_dir_to_file {
599 print STDERR "Node change from directory to file ",
600 "is not supported by Subversion: ",$file,"\n";
603 sub err_file_to_dir {
605 print STDERR "Node change from file to directory ",
606 "is not supported by Subversion: ",$file,"\n";
611 sub svn_checkout_tree {
612 my ($svn_rev, $treeish) = @_;
613 my $from = file_to_s("$REV_DIR/$svn_rev");
615 print "diff-tree $from $treeish\n";
616 my $pid = open my $diff_fh, '-|';
617 defined $pid or croak $!;
619 my @diff_tree = qw(git-diff-tree -z -r);
620 if ($_cp_similarity) {
621 push @diff_tree, "-C$_cp_similarity";
623 push @diff_tree, '-C';
625 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
626 push @diff_tree, "-l$_l" if defined $_l;
627 exec(@diff_tree, $from, $treeish) or croak $!;
629 my $mods = parse_diff_tree($diff_fh);
631 # git can do empty commits, but SVN doesn't allow it...
634 my ($rm, $add) = precommit_check($mods);
636 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
637 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
638 if ($m->{chg} eq 'C') {
639 svn_ensure_parent_path( $m->{file_b} );
640 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
641 apply_mod_line_blob($m);
642 svn_check_prop_executable($m);
643 } elsif ($m->{chg} eq 'D') {
644 sys(qw(svn rm --force), $m->{file_b});
645 } elsif ($m->{chg} eq 'R') {
646 svn_ensure_parent_path( $m->{file_b} );
647 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
648 apply_mod_line_blob($m);
649 svn_check_prop_executable($m);
650 } elsif ($m->{chg} eq 'M') {
651 apply_mod_line_blob($m);
652 svn_check_prop_executable($m);
653 } elsif ($m->{chg} eq 'T') {
654 sys(qw(svn rm --force),$m->{file_b});
655 apply_mod_line_blob($m);
656 sys(qw(svn add --force), $m->{file_b});
657 svn_check_prop_executable($m);
658 } elsif ($m->{chg} eq 'A') {
659 svn_ensure_parent_path( $m->{file_b} );
660 apply_mod_line_blob($m);
661 sys(qw(svn add --force), $m->{file_b});
662 svn_check_prop_executable($m);
664 croak "Invalid chg: $m->{chg}\n";
668 assert_tree($treeish);
669 if ($_rmdir) { # remove empty directories
670 handle_rmdir($rm, $add);
672 assert_tree($treeish);
676 # svn ls doesn't work with respect to the current working tree, but what's
677 # in the repository. There's not even an option for it... *sigh*
678 # (added files don't show up and removed files remain in the ls listing)
680 my ($dir, $rm, $add) = @_;
681 chomp(my @ls = safe_qx('svn','ls',$dir));
684 s#/$##; # trailing slashes are evil
685 push @ret, $_ unless $rm->{$dir}->{$_};
687 if (exists $add->{$dir}) {
688 push @ret, keys %{$add->{$dir}};
696 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
697 my $ls = svn_ls_current($dir, $rm, $add);
698 next if (scalar @$ls);
699 sys(qw(svn rm --force),$dir);
701 my $dn = dirname $dir;
702 $rm->{ $dn }->{ basename $dir } = 1;
703 $ls = svn_ls_current($dn, $rm, $add);
704 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
705 sys(qw(svn rm --force),$dn);
708 $rm->{ $dn }->{ $dir } = 1;
709 $ls = svn_ls_current($dn, $rm, $add);
714 sub svn_commit_tree {
715 my ($svn_rev, $commit) = @_;
716 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
717 my %log_msg = ( msg => '' );
718 open my $msg, '>', $commit_msg or croak $!;
720 chomp(my $type = `git-cat-file -t $commit`);
721 if ($type eq 'commit') {
722 my $pid = open my $msg_fh, '-|';
723 defined $pid or croak $!;
726 exec(qw(git-cat-file commit), $commit) or croak $!;
731 $in_msg = 1 if (/^\s*$/);
732 } elsif (/^git-svn-id: /) {
733 # skip this, we regenerate the correct one
734 # on re-fetch anyways
736 print $msg $_ or croak $!;
739 close $msg_fh or croak $!;
741 close $msg or croak $!;
743 if ($_edit || ($type eq 'tree')) {
744 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
745 system($editor, $commit_msg);
748 # file_to_s removes all trailing newlines, so just use chomp() here:
749 open $msg, '<', $commit_msg or croak $!;
750 { local $/; chomp($log_msg{msg} = <$msg>); }
751 close $msg or croak $!;
753 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
754 print "Committing $commit: $oneline\n";
756 if (defined $LC_ALL) {
757 $ENV{LC_ALL} = $LC_ALL;
761 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
764 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
765 if (!defined $committed) {
766 my $out = join("\n",@ci_output);
767 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
768 $out, "\n\nAssuming English locale...";
769 ($committed) = ($out =~ /^Committed revision \d+\./sm);
770 defined $committed or die " FAILED!\n",
771 "Commit output failed to parse committed revision!\n",
772 print STDERR " OK\n";
775 my @svn_up = qw(svn up);
776 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
777 if ($committed == ($svn_rev + 1)) {
778 push @svn_up, "-r$committed";
780 my $info = svn_info('.');
781 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
782 if ($info->{'Last Changed Rev'} != $committed) {
783 croak "$info->{'Last Changed Rev'} != $committed\n"
785 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
786 /(\d{4})\-(\d\d)\-(\d\d)\s
787 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
788 or croak "Failed to parse date: $date\n";
789 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
790 $log_msg{author} = $info->{'Last Changed Author'};
791 $log_msg{revision} = $committed;
792 $log_msg{msg} .= "\n";
793 my $parent = file_to_s("$REV_DIR/$svn_rev");
794 git_commit(\%log_msg, $parent, $commit);
798 push @svn_up, "-r$svn_rev";
800 return fetch("$committed=$commit")->{revision};
803 # read the entire log into a temporary file (which is removed ASAP)
804 # and store the file handle + parser state
807 my $log_fh = IO::File->new_tmpfile or croak $!;
809 defined $pid or croak $!;
811 open STDOUT, '>&', $log_fh or croak $!;
812 exec (qw(svn log), @log_args) or croak $!
816 seek $log_fh, 0, 0 or croak $!;
817 return { state => 'sep', fh => $log_fh };
821 my $log = shift; # retval of svn_log_raw()
828 if ($log->{state} eq 'msg') {
830 $ret->{msg} .= $_."\n";
831 unless(--$ret->{lines}) {
832 $log->{state} = 'sep';
835 croak "Log parse error at: $_\n",
841 if ($log->{state} ne 'sep') {
842 croak "Log parse error at: $_\n",
843 "state: $log->{state}\n",
847 $log->{state} = 'rev';
849 # if we have an empty log message, put something there:
851 $ret->{msg} ||= "\n";
852 delete $ret->{lines};
857 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
859 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
860 ($lines) = ($lines =~ /(\d+)/);
861 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
862 /(\d{4})\-(\d\d)\-(\d\d)\s
863 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
864 or croak "Failed to parse date: $date\n";
865 $ret = { revision => $rev,
866 date => "$tz $Y-$m-$d $H:$M:$S",
870 if (defined $_authors && ! defined $users{$author}) {
871 die "Author: $author not defined in ",
874 $log->{state} = 'msg_start';
877 # skip the first blank line of the message:
878 if ($log->{state} eq 'msg_start' && /^$/) {
879 $log->{state} = 'msg';
880 } elsif ($log->{state} eq 'msg') {
882 $ret->{msg} .= $_."\n";
883 unless (--$ret->{lines}) {
884 $log->{state} = 'sep';
887 croak "Log parse error at: $_\n",
888 $ret->{revision},"\n";
896 my $url = shift || $SVN_URL;
898 my $pid = open my $info_fh, '-|';
899 defined $pid or croak $!;
902 exec(qw(svn info),$url) or croak $!;
906 # only single-lines seem to exist in svn info output
909 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
911 push @{$ret->{-order}}, $1;
914 close $info_fh or croak $!;
918 sub sys { system(@_) == 0 or croak $? }
921 my ($from, $to) = @_;
922 my $es = svn_propget_base('svn:eol-style', $to);
923 open my $rfd, '<', $from or croak $!;
924 binmode $rfd or croak $!;
925 open my $wfd, '>', $to or croak $!;
926 binmode $wfd or croak $!;
928 my $eol = $EOL{$es} or undef;
933 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
936 if ($buf =~ /\015$/) {
938 defined($r = sysread($rfd,$c,1)) or croak $!;
939 $buf .= $c if $r > 0;
941 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
944 for ($w = 0; $w < $r; $w += $t) {
945 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
951 sub do_update_index {
952 my ($z_cmd, $cmd, $no_text_base) = @_;
954 my $z = open my $p, '-|';
955 defined $z or croak $!;
956 unless ($z) { exec @$z_cmd or croak $! }
958 my $pid = open my $ui, '|-';
959 defined $pid or croak $!;
961 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
964 while (my $x = <$p>) {
966 if (!$no_text_base && lstat $x && ! -l _ &&
967 svn_propget_base('svn:keywords', $x)) {
968 my $mode = -x _ ? 0755 : 0644;
969 my ($v,$d,$f) = File::Spec->splitpath($x);
970 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
971 'text-base',"$f.svn-base");
974 $tb = File::Spec->catfile($d, '.svn',
975 'text-base',"$f.svn-base");
978 unlink $x or croak $!;
980 chmod(($mode &~ umask), $x) or croak $!;
984 close $ui or croak $!;
988 my $no_text_base = shift;
989 do_update_index([qw/git-diff-files --name-only -z/],
992 do_update_index([qw/git-ls-files -z --others/,
993 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
999 my ($str, $file, $mode) = @_;
1000 open my $fd,'>',$file or croak $!;
1001 print $fd $str,"\n" or croak $!;
1002 close $fd or croak $!;
1003 chmod ($mode &~ umask, $file) if (defined $mode);
1008 open my $fd,'<',$file or croak "$!: file: $file\n";
1011 close $fd or croak $!;
1016 sub assert_revision_unknown {
1018 if (-f "$REV_DIR/$revno") {
1019 croak "$REV_DIR/$revno already exists! ",
1020 "Why are we refetching it?";
1026 my @x = safe_qx('git-cat-file','commit',$x);
1027 my @y = safe_qx('git-cat-file','commit',$y);
1028 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1029 || $y[0] !~ /^tree $sha1\n$/) {
1030 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1036 sub assert_revision_eq_or_unknown {
1037 my ($revno, $commit) = @_;
1038 if (-f "$REV_DIR/$revno") {
1039 my $current = file_to_s("$REV_DIR/$revno");
1040 if (($commit ne $current) && !trees_eq($commit, $current)) {
1041 croak "$REV_DIR/$revno already exists!\n",
1042 "current: $current\nexpected: $commit\n";
1049 my ($log_msg, @parents) = @_;
1050 assert_revision_unknown($log_msg->{revision});
1051 my $out_fh = IO::File->new_tmpfile or croak $!;
1053 map_tree_joins() if (@_branch_from && !%tree_map);
1055 # commit parents can be conditionally bound to a particular
1056 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1058 foreach my $p (@parents) {
1059 next unless defined $p;
1060 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1061 if ($1 == $log_msg->{revision}) {
1062 push @exec_parents, $2;
1065 push @exec_parents, $p if $p =~ /$sha1_short/o;
1070 defined $pid or croak $!;
1072 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1074 chomp(my $tree = `git-write-tree`);
1076 if (exists $tree_map{$tree}) {
1077 my %seen_parent = map { $_ => 1 } @exec_parents;
1078 foreach (@{$tree_map{$tree}}) {
1079 # MAXPARENT is defined to 16 in commit-tree.c:
1080 if ($seen_parent{$_} || @exec_parents > 16) {
1083 push @exec_parents, $_;
1084 $seen_parent{$_} = 1;
1087 my $msg_fh = IO::File->new_tmpfile or croak $!;
1088 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1089 "$SVN_URL\@$log_msg->{revision}",
1090 " $SVN_UUID\n" or croak $!;
1091 $msg_fh->flush == 0 or croak $!;
1092 seek $msg_fh, 0, 0 or croak $!;
1094 set_commit_env($log_msg);
1096 my @exec = ('git-commit-tree',$tree);
1097 push @exec, '-p', $_ foreach @exec_parents;
1098 open STDIN, '<&', $msg_fh or croak $!;
1099 open STDOUT, '>&', $out_fh or croak $!;
1100 exec @exec or croak $!;
1105 $out_fh->flush == 0 or croak $!;
1106 seek $out_fh, 0, 0 or croak $!;
1107 chomp(my $commit = do { local $/; <$out_fh> });
1108 if ($commit !~ /^$sha1$/o) {
1109 croak "Failed to commit, invalid sha1: $commit\n";
1111 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1112 if (my $primary_parent = shift @exec_parents) {
1114 defined $pid or croak $!;
1118 exec 'git-rev-parse','--verify',
1119 "refs/remotes/$GIT_SVN^0" or croak $!;
1122 push @update_ref, $primary_parent unless $?;
1125 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
1126 print "r$log_msg->{revision} = $commit\n";
1127 if ($_repack && (--$_repack_nr == 0)) {
1128 $_repack_nr = $_repack;
1129 sys("git repack $_repack_flags");
1134 sub set_commit_env {
1136 my $author = $log_msg->{author};
1137 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1138 : ($author,"$author\@$SVN_UUID");
1139 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1140 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1141 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1144 sub apply_mod_line_blob {
1146 if ($m->{mode_b} =~ /^120/) {
1147 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1149 blob_to_file($m->{sha1_b}, $m->{file_b});
1153 sub blob_to_symlink {
1154 my ($blob, $link) = @_;
1155 defined $link or croak "\$link not defined!\n";
1156 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1157 if (-l $link || -f _) {
1158 unlink $link or croak $!;
1161 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1162 symlink $dest, $link or croak $!;
1166 my ($blob, $file) = @_;
1167 defined $file or croak "\$file not defined!\n";
1168 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1169 if (-l $file || -f _) {
1170 unlink $file or croak $!;
1173 open my $blob_fh, '>', $file or croak "$!: $file\n";
1175 defined $pid or croak $!;
1178 open STDOUT, '>&', $blob_fh or croak $!;
1179 exec('git-cat-file','blob',$blob) or croak $!;
1184 close $blob_fh or croak $!;
1188 my $pid = open my $child, '-|';
1189 defined $pid or croak $!;
1191 exec(@_) or croak $!;
1193 my @ret = (<$child>);
1194 close $child or croak $?;
1195 die $? if $?; # just in case close didn't error out
1196 return wantarray ? @ret : join('',@ret);
1199 sub svn_compat_check {
1200 my @co_help = safe_qx(qw(svn co -h));
1201 unless (grep /ignore-externals/,@co_help) {
1202 print STDERR "W: Installed svn version does not support ",
1203 "--ignore-externals\n";
1204 $_no_ignore_ext = 1;
1206 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1207 $_svn_co_url_revs = 1;
1209 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1210 $_svn_pg_peg_revs = 1;
1213 # I really, really hope nobody hits this...
1214 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1216 W: The installed svn version does not support the --stop-on-copy flag in
1218 Lets hope the directory you're tracking is not a branch or tag
1219 and was never moved within the repository...
1225 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1226 # (and they won't honor URL@<rev> without -r<rev>, too!)
1227 sub svn_cmd_checkout {
1228 my ($url, $rev, $dir) = @_;
1229 my @cmd = ('svn','co', "-r$rev");
1230 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1231 $url .= "\@$rev" if $_svn_co_url_revs;
1232 sys(@cmd, $url, $dir);
1235 sub check_upgrade_needed {
1237 my $pid = open my $child, '-|';
1238 defined $pid or croak $!;
1241 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1243 my @ret = (<$child>);
1244 close $child or croak $?;
1245 die $? if $?; # just in case close didn't error out
1246 return wantarray ? @ret : join('',@ret);
1249 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1251 print STDERR "Please run: $0 rebuild --upgrade\n";
1256 # fills %tree_map with a reverse mapping of trees to commits. Useful
1257 # for finding parents to commit on.
1258 sub map_tree_joins {
1260 foreach my $br (@_branch_from) {
1261 my $pid = open my $pipe, '-|';
1262 defined $pid or croak $!;
1264 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1268 if (/^commit ($sha1)$/o) {
1271 # if we've seen a commit,
1272 # we've seen its parents
1273 last if $seen{$commit};
1274 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1275 unless (defined $tree) {
1276 die "Failed to parse commit $commit\n";
1278 push @{$tree_map{$tree}}, $commit;
1282 close $pipe; # we could be breaking the pipe early
1287 if (@_branch_from) {
1288 print STDERR '--branch|-b parameters are ignored when ',
1289 "--branch-all-refs|-B is passed\n";
1292 # don't worry about rev-list on non-commit objects/tags,
1293 # it shouldn't blow up if a ref is a blob or tree...
1294 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1297 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1299 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1300 while (<$authors>) {
1302 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1303 my ($user, $name, $email) = ($1, $2, $3);
1304 $users{$user} = [$name, $email];
1306 close $authors or croak $!;
1309 sub svn_propget_base {
1311 $f .= '@BASE' if $_svn_pg_peg_revs;
1312 return safe_qx(qw/svn propget/, $p, $f);
1315 sub migration_check {
1316 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1317 print "Upgrading repository...\n";
1318 unless (-d "$GIT_DIR/svn") {
1319 mkdir "$GIT_DIR/svn" or croak $!;
1321 print "Data from a previous version of git-svn exists, but\n\t",
1322 "$GIT_SVN_DIR\n\t(required for this version ",
1323 "($VERSION) of git-svn) does not.\n";
1325 foreach my $x (`git-rev-parse --symbolic --all`) {
1326 next unless $x =~ s#^refs/remotes/##;
1328 next unless -f "$GIT_DIR/$x/info/url";
1329 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1331 my $dn = dirname("$GIT_DIR/svn/$x");
1332 mkpath([$dn]) unless -d $dn;
1333 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1334 my ($url, $path) = repo_path_split($u);
1335 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
1336 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
1338 print "Done upgrading.\n";
1342 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1343 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1344 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1346 $REV_DIR = "$GIT_SVN_DIR/revs";
1347 $SVN_WC = "$GIT_SVN_DIR/tree";
1350 # convert GetOpt::Long specs for use by git-repo-config
1351 sub read_repo_config {
1352 return unless -d $GIT_DIR;
1354 foreach my $o (keys %$opts) {
1355 my $v = $opts->{$o};
1356 my ($key) = ($o =~ /^([a-z\-]+)/);
1358 my $arg = 'git-repo-config';
1359 $arg .= ' --int' if ($o =~ /[:=]i$/);
1360 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1361 if (ref $v eq 'ARRAY') {
1362 chomp(my @tmp = `$arg --get-all svn.$key`);
1365 chomp(my $tmp = `$arg --get svn.$key`);
1366 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
1373 sub set_default_vals {
1374 if (defined $_repack) {
1375 $_repack = 1000 if ($_repack <= 0);
1376 $_repack_nr = $_repack;
1377 $_repack_flags ||= '';
1385 $svn_log hashref (as returned by svn_log_raw)
1387 fh => file handle of the log file,
1388 state => state of the log file parser (sep/msg/rev/msg_start...)
1391 $log_msg hashref as returned by next_log_entry($svn_log)
1393 msg => 'whitespace-formatted log entry
1394 ', # trailing newline is preserved
1395 revision => '8', # integer
1396 date => '2004-02-24T17:01:44.108345Z', # commit date
1397 author => 'committer name'
1401 @mods = array of diff-index line hashes, each element represents one line
1402 of diff-index output
1404 diff-index line ($m hash)
1406 mode_a => first column of diff-index output, no leading ':',
1407 mode_b => second column of diff-index output,
1408 sha1_b => sha1sum of the final blob,
1409 chg => change type [MCRADT],
1410 file_a => original file name of a file (iff chg is 'C' or 'R')
1411 file_b => new/current file name of a file (any chg)