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 $_version, $_upgrade, $_authors, $_branch_all_refs);
38 my (@_branch_from, %tree_map, %users);
39 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
40 my @repo_path_split_cache;
42 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
43 'branch|b=s' => \@_branch_from,
44 'branch-all-refs|B' => \$_branch_all_refs,
45 'authors-file|A=s' => \$_authors );
47 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
48 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
51 fetch => [ \&fetch, "Download new revisions from SVN",
52 { 'revision|r=s' => \$_revision, %fc_opts } ],
53 init => [ \&init, "Initialize a repo for tracking" .
54 " (requires URL argument)", { } ],
55 commit => [ \&commit, "Commit git revisions to SVN",
56 { 'stdin|' => \$_stdin,
59 'find-copies-harder' => \$_find_copies_harder,
61 'copy-similarity|C=i'=> \$_cp_similarity,
64 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
65 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
66 { 'no-ignore-externals' => \$_no_ignore_ext,
67 'upgrade' => \$_upgrade } ],
70 for (my $i = 0; $i < @ARGV; $i++) {
71 if (defined $cmd{$ARGV[$i]}) {
78 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
80 # convert GetOpt::Long specs for use by git-repo-config
81 foreach my $o (keys %opts) {
83 my ($key) = ($o =~ /^([a-z\-]+)/);
85 my $arg = 'git-repo-config';
86 $arg .= ' --int' if ($o =~ /=i$/);
87 $arg .= ' --bool' if ($o !~ /=[sfi]$/);
88 if (ref $v eq 'ARRAY') {
89 chomp(my @tmp = `$arg --get-all svn.$key`);
92 chomp(my $tmp = `$arg --get svn.$key`);
93 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
99 GetOptions(%opts, 'help|H|h' => \$_help,
100 'version|V' => \$_version,
101 'id|i=s' => \$GIT_SVN) or exit 1;
103 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
104 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
105 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
107 $REV_DIR = "$GIT_SVN_DIR/revs";
108 $SVN_WC = "$GIT_SVN_DIR/tree";
111 version() if $_version;
112 usage(1) unless defined $cmd;
113 load_authors() if $_authors;
114 load_all_refs() if $_branch_all_refs;
116 migration_check() unless $cmd eq 'init';
117 $cmd{$cmd}->[0]->(@ARGV);
120 ####################### primary functions ######################
122 my $exit = shift || 0;
123 my $fd = $exit ? \*STDERR : \*STDOUT;
125 git-svn - bidirectional operations between a single Subversion tree and git
126 Usage: $0 <command> [options] [arguments]\n
128 print $fd "Available commands:\n" unless $cmd;
130 foreach (sort keys %cmd) {
131 next if $cmd && $cmd ne $_;
132 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
133 foreach (keys %{$cmd{$_}->[2]}) {
134 # prints out arguments as they should be passed:
135 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
136 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
138 split /\|/,$_)," $x\n";
142 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
143 arbitrary identifier if you're tracking multiple SVN branches/repositories in
144 one git repository and want to keep them separate. See git-svn(1) for more
151 print "git-svn version $VERSION\n";
156 $SVN_URL = shift or undef;
159 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
161 check_upgrade_needed();
164 my $pid = open(my $rev_list,'-|');
165 defined $pid or croak $!;
167 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
170 while (<$rev_list>) {
173 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
174 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
175 next if (!@commit); # skip merges
176 my $id = $commit[$#commit];
177 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
179 if (!$rev || !$uuid || !$url) {
180 # some of the original repositories I made had
181 # indentifiers like this:
182 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
184 if (!$rev || !$uuid) {
185 croak "Unable to extract revision or UUID from ",
190 # if we merged or otherwise started elsewhere, this is
191 # how we break out of it
192 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
193 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
195 print "r$rev = $c\n";
196 unless (defined $latest) {
197 if (!$SVN_URL && !$url) {
198 croak "SVN repository location required: $url\n";
205 assert_revision_eq_or_unknown($rev, $c);
206 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
207 $newest_rev = $rev if ($rev > $newest_rev);
209 close $rev_list or croak $?;
210 if (!chdir $SVN_WC) {
211 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
212 chdir $SVN_WC or croak $!;
216 defined $pid or croak $!;
218 my @svn_up = qw(svn up);
219 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
220 sys(@svn_up,"-r$newest_rev");
221 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
223 exec('git-write-tree');
229 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
230 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
236 $SVN_URL = shift or die "SVN repository location required " .
237 "as a command-line argument\n";
238 unless (-d $GIT_DIR) {
246 check_upgrade_needed();
247 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
248 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
249 unless ($_revision) {
250 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
252 push @log_args, "-r$_revision";
253 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
255 my $svn_log = svn_log_raw(@log_args);
257 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
258 my $last_commit = undef;
259 unless (-d $SVN_WC) {
260 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
261 chdir $SVN_WC or croak $!;
263 $last_commit = git_commit($base, @parents);
264 assert_tree($last_commit);
266 chdir $SVN_WC or croak $!;
268 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
269 # looks like a user manually cp'd and svn switch'ed
270 unless ($last_commit) {
271 sys(qw/svn revert -R ./);
272 assert_svn_wc_clean($base->{revision});
273 $last_commit = git_commit($base, @parents);
274 assert_tree($last_commit);
277 my @svn_up = qw(svn up);
278 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
280 while (my $log_msg = next_log_entry($svn_log)) {
281 assert_tree($last_commit);
282 if ($last->{revision} >= $log_msg->{revision}) {
283 croak "Out of order: last >= current: ",
284 "$last->{revision} >= $log_msg->{revision}\n";
286 # Revert is needed for cases like:
287 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
288 # I can't seem to reproduce something like that on a test...
289 sys(qw/svn revert -R ./);
290 assert_svn_wc_clean($last->{revision});
291 sys(@svn_up,"-r$log_msg->{revision}");
292 $last_commit = git_commit($log_msg, $last_commit, @parents);
295 unless (-e "$GIT_DIR/refs/heads/master") {
296 sys(qw(git-update-ref refs/heads/master),$last_commit);
303 check_upgrade_needed();
304 if ($_stdin || !@commits) {
305 print "Reading from stdin...\n";
308 if (/\b($sha1_short)\b/o) {
309 unshift @commits, $1;
314 foreach my $c (@commits) {
315 chomp(my @tmp = safe_qx('git-rev-parse',$c));
316 if (scalar @tmp == 1) {
318 } elsif (scalar @tmp > 1) {
319 push @revs, reverse (safe_qx('git-rev-list',@tmp));
321 die "Failed to rev-parse $c\n";
326 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
327 my $info = svn_info('.');
328 my $fetched = fetch();
329 if ($info->{Revision} != $fetched->{revision}) {
330 print STDERR "There are new revisions that were fetched ",
331 "and need to be merged (or acknowledged) ",
332 "before committing.\n";
335 $info = svn_info('.');
337 my $svn_current_rev = $info->{'Last Changed Rev'};
338 foreach my $c (@revs) {
339 my $mods = svn_checkout_tree($svn_current_rev, $c);
340 if (scalar @$mods == 0) {
341 print "Skipping, no changes detected\n";
344 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
346 print "Done committing ",scalar @revs," revisions to SVN\n";
350 require File::Find or die $!;
351 my $exclude_file = "$GIT_DIR/info/exclude";
352 open my $fh, '<', $exclude_file or croak $!;
353 chomp(my @excludes = (<$fh>));
354 close $fh or croak $!;
356 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
357 chdir $SVN_WC or croak $!;
359 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
361 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
362 }}, no_chdir=>1},'.');
365 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
367 foreach my $i (sort keys %ign) {
368 print "\n# ",$i,"\n";
369 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
373 ########################### utility functions #########################
377 my $info = shift || svn_info('.');
378 $SVN_UUID = $info->{'Repository UUID'} or
379 croak "Repository UUID unreadable\n";
380 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
385 defined $pid or croak $!;
387 open my $null, '>', '/dev/null' or croak $!;
388 open STDERR, '>&', $null or croak $!;
389 open STDOUT, '>&', $null or croak $!;
396 sub repo_path_split {
397 my $full_url = shift;
398 $full_url =~ s#/+$##;
400 foreach (@repo_path_split_cache) {
401 if ($full_url =~ s#$_##) {
403 $full_url =~ s#^/+##;
404 return ($u, $full_url);
408 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
410 my @paths = split(m#/+#, $path);
412 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
413 my $n = shift @paths || last;
416 push @repo_path_split_cache, qr/^(\Q$url\E)/;
417 return ($url, $path);
421 defined $SVN_URL or croak "SVN repository location required\n";
422 unless (-d $GIT_DIR) {
423 croak "GIT_DIR=$GIT_DIR does not exist!\n";
425 mkpath([$GIT_SVN_DIR]);
426 mkpath(["$GIT_SVN_DIR/info"]);
428 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
430 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
431 print $fd '.svn',"\n";
432 close $fd or croak $!;
433 my ($url, $path) = repo_path_split($SVN_URL);
434 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
435 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
438 sub assert_svn_wc_clean {
440 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
441 my $lcr = svn_info('.')->{'Last Changed Rev'};
442 if ($svn_rev != $lcr) {
443 print STDERR "Checking for copy-tree ... ";
444 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
445 "-r$lcr:$svn_rev")));
447 croak "Nope! Expected r$svn_rev, got r$lcr\n";
449 print STDERR "OK!\n";
452 my @status = grep(!/^Performing status on external/,(`svn status`));
453 @status = grep(!/^\s*$/,@status);
454 if (scalar @status) {
455 print STDERR "Tree ($SVN_WC) is not clean:\n";
456 print STDERR $_ foreach @status;
463 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
464 chomp(my $type = `git-cat-file -t $treeish`);
466 while ($type eq 'tag') {
467 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
469 if ($type eq 'commit') {
470 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
471 ($expected) = ($expected =~ /^tree ($sha1)$/);
472 die "Unable to get tree from $treeish\n" unless $expected;
473 } elsif ($type eq 'tree') {
474 $expected = $treeish;
476 die "$treeish is a $type, expected tree, tag or commit\n";
479 my $old_index = $ENV{GIT_INDEX_FILE};
480 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
482 unlink $tmpindex or croak $!;
484 $ENV{GIT_INDEX_FILE} = $tmpindex;
486 chomp(my $tree = `git-write-tree`);
488 $ENV{GIT_INDEX_FILE} = $old_index;
490 delete $ENV{GIT_INDEX_FILE};
492 if ($tree ne $expected) {
493 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
498 sub parse_diff_tree {
504 chomp $_; # this gets rid of the trailing "\0"
505 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
506 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
507 push @mods, { mode_a => $1, mode_b => $2,
508 sha1_b => $3, chg => $4 };
509 if ($4 =~ /^(?:C|R)$/) {
514 } elsif ($state eq 'file_a') {
515 my $x = $mods[$#mods] or croak "Empty array\n";
516 if ($x->{chg} !~ /^(?:C|R)$/) {
517 croak "Error parsing $_, $x->{chg}\n";
521 } elsif ($state eq 'file_b') {
522 my $x = $mods[$#mods] or croak "Empty array\n";
523 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
524 croak "Error parsing $_, $x->{chg}\n";
526 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
527 croak "Error parsing $_, $x->{chg}\n";
532 croak "Error parsing $_\n";
535 close $diff_fh or croak $!;
540 sub svn_check_prop_executable {
542 return if -l $m->{file_b};
543 if ($m->{mode_b} =~ /755$/) {
544 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
545 if ($m->{mode_a} !~ /755$/) {
546 sys(qw(svn propset svn:executable 1), $m->{file_b});
548 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
549 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
550 sys(qw(svn propdel svn:executable), $m->{file_b});
551 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
552 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
556 sub svn_ensure_parent_path {
557 my $dir_b = dirname(shift);
558 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
559 mkpath([$dir_b]) unless (-d $dir_b);
560 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
563 sub precommit_check {
565 my (%rm_file, %rmdir_check, %added_check);
567 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
568 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
569 if ($m->{chg} eq 'R') {
570 if (-d $m->{file_b}) {
571 err_dir_to_file("$m->{file_a} => $m->{file_b}");
573 # dir/$file => dir/file/$file
574 my $dirname = dirname($m->{file_b});
575 while ($dirname ne File::Spec->curdir) {
576 if ($dirname ne $m->{file_a}) {
577 $dirname = dirname($dirname);
580 err_file_to_dir("$m->{file_a} => $m->{file_b}");
582 # baz/zzz => baz (baz is a file)
583 $dirname = dirname($m->{file_a});
584 while ($dirname ne File::Spec->curdir) {
585 if ($dirname ne $m->{file_b}) {
586 $dirname = dirname($dirname);
589 err_dir_to_file("$m->{file_a} => $m->{file_b}");
592 if ($m->{chg} =~ /^(D|R)$/) {
593 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
594 $rm_file{ $m->{$t} } = 1;
595 my $dirname = dirname( $m->{$t} );
596 my $basename = basename( $m->{$t} );
597 $rmdir_check{$dirname}->{$basename} = 1;
598 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
599 if (-d $m->{file_b}) {
600 err_dir_to_file($m->{file_b});
602 my $dirname = dirname( $m->{file_b} );
603 my $basename = basename( $m->{file_b} );
604 $added_check{$dirname}->{$basename} = 1;
605 while ($dirname ne File::Spec->curdir) {
606 if ($rm_file{$dirname}) {
607 err_file_to_dir($m->{file_b});
609 $dirname = dirname $dirname;
613 return (\%rmdir_check, \%added_check);
615 sub err_dir_to_file {
617 print STDERR "Node change from directory to file ",
618 "is not supported by Subversion: ",$file,"\n";
621 sub err_file_to_dir {
623 print STDERR "Node change from file to directory ",
624 "is not supported by Subversion: ",$file,"\n";
629 sub svn_checkout_tree {
630 my ($svn_rev, $treeish) = @_;
631 my $from = file_to_s("$REV_DIR/$svn_rev");
633 print "diff-tree $from $treeish\n";
634 my $pid = open my $diff_fh, '-|';
635 defined $pid or croak $!;
637 my @diff_tree = qw(git-diff-tree -z -r);
638 if ($_cp_similarity) {
639 push @diff_tree, "-C$_cp_similarity";
641 push @diff_tree, '-C';
643 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
644 push @diff_tree, "-l$_l" if defined $_l;
645 exec(@diff_tree, $from, $treeish) or croak $!;
647 my $mods = parse_diff_tree($diff_fh);
649 # git can do empty commits, but SVN doesn't allow it...
652 my ($rm, $add) = precommit_check($mods);
654 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
655 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
656 if ($m->{chg} eq 'C') {
657 svn_ensure_parent_path( $m->{file_b} );
658 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
659 apply_mod_line_blob($m);
660 svn_check_prop_executable($m);
661 } elsif ($m->{chg} eq 'D') {
662 sys(qw(svn rm --force), $m->{file_b});
663 } elsif ($m->{chg} eq 'R') {
664 svn_ensure_parent_path( $m->{file_b} );
665 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
666 apply_mod_line_blob($m);
667 svn_check_prop_executable($m);
668 } elsif ($m->{chg} eq 'M') {
669 apply_mod_line_blob($m);
670 svn_check_prop_executable($m);
671 } elsif ($m->{chg} eq 'T') {
672 sys(qw(svn rm --force),$m->{file_b});
673 apply_mod_line_blob($m);
674 sys(qw(svn add --force), $m->{file_b});
675 svn_check_prop_executable($m);
676 } elsif ($m->{chg} eq 'A') {
677 svn_ensure_parent_path( $m->{file_b} );
678 apply_mod_line_blob($m);
679 sys(qw(svn add --force), $m->{file_b});
680 svn_check_prop_executable($m);
682 croak "Invalid chg: $m->{chg}\n";
686 assert_tree($treeish);
687 if ($_rmdir) { # remove empty directories
688 handle_rmdir($rm, $add);
690 assert_tree($treeish);
694 # svn ls doesn't work with respect to the current working tree, but what's
695 # in the repository. There's not even an option for it... *sigh*
696 # (added files don't show up and removed files remain in the ls listing)
698 my ($dir, $rm, $add) = @_;
699 chomp(my @ls = safe_qx('svn','ls',$dir));
702 s#/$##; # trailing slashes are evil
703 push @ret, $_ unless $rm->{$dir}->{$_};
705 if (exists $add->{$dir}) {
706 push @ret, keys %{$add->{$dir}};
714 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
715 my $ls = svn_ls_current($dir, $rm, $add);
716 next if (scalar @$ls);
717 sys(qw(svn rm --force),$dir);
719 my $dn = dirname $dir;
720 $rm->{ $dn }->{ basename $dir } = 1;
721 $ls = svn_ls_current($dn, $rm, $add);
722 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
723 sys(qw(svn rm --force),$dn);
726 $rm->{ $dn }->{ $dir } = 1;
727 $ls = svn_ls_current($dn, $rm, $add);
732 sub svn_commit_tree {
733 my ($svn_rev, $commit) = @_;
734 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
735 my %log_msg = ( msg => '' );
736 open my $msg, '>', $commit_msg or croak $!;
738 chomp(my $type = `git-cat-file -t $commit`);
739 if ($type eq 'commit') {
740 my $pid = open my $msg_fh, '-|';
741 defined $pid or croak $!;
744 exec(qw(git-cat-file commit), $commit) or croak $!;
749 $in_msg = 1 if (/^\s*$/);
750 } elsif (/^git-svn-id: /) {
751 # skip this, we regenerate the correct one
752 # on re-fetch anyways
754 print $msg $_ or croak $!;
757 close $msg_fh or croak $!;
759 close $msg or croak $!;
761 if ($_edit || ($type eq 'tree')) {
762 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
763 system($editor, $commit_msg);
766 # file_to_s removes all trailing newlines, so just use chomp() here:
767 open $msg, '<', $commit_msg or croak $!;
768 { local $/; chomp($log_msg{msg} = <$msg>); }
769 close $msg or croak $!;
771 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
772 print "Committing $commit: $oneline\n";
774 if (defined $LC_ALL) {
775 $ENV{LC_ALL} = $LC_ALL;
779 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
782 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
783 if (!defined $committed) {
784 my $out = join("\n",@ci_output);
785 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
786 $out, "\n\nAssuming English locale...";
787 ($committed) = ($out =~ /^Committed revision \d+\./sm);
788 defined $committed or die " FAILED!\n",
789 "Commit output failed to parse committed revision!\n",
790 print STDERR " OK\n";
793 my @svn_up = qw(svn up);
794 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
795 if ($committed == ($svn_rev + 1)) {
796 push @svn_up, "-r$committed";
798 my $info = svn_info('.');
799 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
800 if ($info->{'Last Changed Rev'} != $committed) {
801 croak "$info->{'Last Changed Rev'} != $committed\n"
803 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
804 /(\d{4})\-(\d\d)\-(\d\d)\s
805 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
806 or croak "Failed to parse date: $date\n";
807 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
808 $log_msg{author} = $info->{'Last Changed Author'};
809 $log_msg{revision} = $committed;
810 $log_msg{msg} .= "\n";
811 my $parent = file_to_s("$REV_DIR/$svn_rev");
812 git_commit(\%log_msg, $parent, $commit);
816 push @svn_up, "-r$svn_rev";
818 return fetch("$committed=$commit")->{revision};
821 # read the entire log into a temporary file (which is removed ASAP)
822 # and store the file handle + parser state
825 my $log_fh = IO::File->new_tmpfile or croak $!;
827 defined $pid or croak $!;
829 open STDOUT, '>&', $log_fh or croak $!;
830 exec (qw(svn log), @log_args) or croak $!
834 seek $log_fh, 0, 0 or croak $!;
835 return { state => 'sep', fh => $log_fh };
839 my $log = shift; # retval of svn_log_raw()
846 if ($log->{state} eq 'msg') {
848 $ret->{msg} .= $_."\n";
849 unless(--$ret->{lines}) {
850 $log->{state} = 'sep';
853 croak "Log parse error at: $_\n",
859 if ($log->{state} ne 'sep') {
860 croak "Log parse error at: $_\n",
861 "state: $log->{state}\n",
865 $log->{state} = 'rev';
867 # if we have an empty log message, put something there:
869 $ret->{msg} ||= "\n";
870 delete $ret->{lines};
875 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
877 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
878 ($lines) = ($lines =~ /(\d+)/);
879 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
880 /(\d{4})\-(\d\d)\-(\d\d)\s
881 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
882 or croak "Failed to parse date: $date\n";
883 $ret = { revision => $rev,
884 date => "$tz $Y-$m-$d $H:$M:$S",
888 if (defined $_authors && ! defined $users{$author}) {
889 die "Author: $author not defined in ",
892 $log->{state} = 'msg_start';
895 # skip the first blank line of the message:
896 if ($log->{state} eq 'msg_start' && /^$/) {
897 $log->{state} = 'msg';
898 } elsif ($log->{state} eq 'msg') {
900 $ret->{msg} .= $_."\n";
901 unless (--$ret->{lines}) {
902 $log->{state} = 'sep';
905 croak "Log parse error at: $_\n",
906 $ret->{revision},"\n";
914 my $url = shift || $SVN_URL;
916 my $pid = open my $info_fh, '-|';
917 defined $pid or croak $!;
920 exec(qw(svn info),$url) or croak $!;
924 # only single-lines seem to exist in svn info output
927 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
929 push @{$ret->{-order}}, $1;
932 close $info_fh or croak $!;
936 sub sys { system(@_) == 0 or croak $? }
939 my ($from, $to) = @_;
940 my $es = svn_propget_base('svn:eol-style', $to);
941 open my $rfd, '<', $from or croak $!;
942 binmode $rfd or croak $!;
943 open my $wfd, '>', $to or croak $!;
944 binmode $wfd or croak $!;
946 my $eol = $EOL{$es} or undef;
951 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
954 if ($buf =~ /\015$/) {
956 defined($r = sysread($rfd,$c,1)) or croak $!;
957 $buf .= $c if $r > 0;
959 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
962 for ($w = 0; $w < $r; $w += $t) {
963 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
969 sub do_update_index {
970 my ($z_cmd, $cmd, $no_text_base) = @_;
972 my $z = open my $p, '-|';
973 defined $z or croak $!;
974 unless ($z) { exec @$z_cmd or croak $! }
976 my $pid = open my $ui, '|-';
977 defined $pid or croak $!;
979 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
982 while (my $x = <$p>) {
984 if (!$no_text_base && lstat $x && ! -l _ &&
985 svn_propget_base('svn:keywords', $x)) {
986 my $mode = -x _ ? 0755 : 0644;
987 my ($v,$d,$f) = File::Spec->splitpath($x);
988 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
989 'text-base',"$f.svn-base");
992 $tb = File::Spec->catfile($d, '.svn',
993 'text-base',"$f.svn-base");
996 unlink $x or croak $!;
998 chmod(($mode &~ umask), $x) or croak $!;
1002 close $ui or croak $!;
1006 my $no_text_base = shift;
1007 do_update_index([qw/git-diff-files --name-only -z/],
1010 do_update_index([qw/git-ls-files -z --others/,
1011 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1017 my ($str, $file, $mode) = @_;
1018 open my $fd,'>',$file or croak $!;
1019 print $fd $str,"\n" or croak $!;
1020 close $fd or croak $!;
1021 chmod ($mode &~ umask, $file) if (defined $mode);
1026 open my $fd,'<',$file or croak "$!: file: $file\n";
1029 close $fd or croak $!;
1034 sub assert_revision_unknown {
1036 if (-f "$REV_DIR/$revno") {
1037 croak "$REV_DIR/$revno already exists! ",
1038 "Why are we refetching it?";
1044 my @x = safe_qx('git-cat-file','commit',$x);
1045 my @y = safe_qx('git-cat-file','commit',$y);
1046 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1047 || $y[0] !~ /^tree $sha1\n$/) {
1048 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1054 sub assert_revision_eq_or_unknown {
1055 my ($revno, $commit) = @_;
1056 if (-f "$REV_DIR/$revno") {
1057 my $current = file_to_s("$REV_DIR/$revno");
1058 if (($commit ne $current) && !trees_eq($commit, $current)) {
1059 croak "$REV_DIR/$revno already exists!\n",
1060 "current: $current\nexpected: $commit\n";
1067 my ($log_msg, @parents) = @_;
1068 assert_revision_unknown($log_msg->{revision});
1069 my $out_fh = IO::File->new_tmpfile or croak $!;
1071 map_tree_joins() if (@_branch_from && !%tree_map);
1073 # commit parents can be conditionally bound to a particular
1074 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1076 foreach my $p (@parents) {
1077 next unless defined $p;
1078 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1079 if ($1 == $log_msg->{revision}) {
1080 push @exec_parents, $2;
1083 push @exec_parents, $p if $p =~ /$sha1_short/o;
1088 defined $pid or croak $!;
1090 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1092 chomp(my $tree = `git-write-tree`);
1094 if (exists $tree_map{$tree}) {
1095 my %seen_parent = map { $_ => 1 } @exec_parents;
1096 foreach (@{$tree_map{$tree}}) {
1097 # MAXPARENT is defined to 16 in commit-tree.c:
1098 if ($seen_parent{$_} || @exec_parents > 16) {
1101 push @exec_parents, $_;
1102 $seen_parent{$_} = 1;
1105 my $msg_fh = IO::File->new_tmpfile or croak $!;
1106 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1107 "$SVN_URL\@$log_msg->{revision}",
1108 " $SVN_UUID\n" or croak $!;
1109 $msg_fh->flush == 0 or croak $!;
1110 seek $msg_fh, 0, 0 or croak $!;
1112 set_commit_env($log_msg);
1114 my @exec = ('git-commit-tree',$tree);
1115 push @exec, '-p', $_ foreach @exec_parents;
1116 open STDIN, '<&', $msg_fh or croak $!;
1117 open STDOUT, '>&', $out_fh or croak $!;
1118 exec @exec or croak $!;
1123 $out_fh->flush == 0 or croak $!;
1124 seek $out_fh, 0, 0 or croak $!;
1125 chomp(my $commit = do { local $/; <$out_fh> });
1126 if ($commit !~ /^$sha1$/o) {
1127 croak "Failed to commit, invalid sha1: $commit\n";
1129 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1130 if (my $primary_parent = shift @exec_parents) {
1132 defined $pid or croak $!;
1136 exec 'git-rev-parse','--verify',
1137 "refs/remotes/$GIT_SVN^0";
1140 push @update_ref, $primary_parent unless $?;
1143 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
1144 print "r$log_msg->{revision} = $commit\n";
1148 sub set_commit_env {
1150 my $author = $log_msg->{author};
1151 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1152 : ($author,"$author\@$SVN_UUID");
1153 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1154 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1155 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1158 sub apply_mod_line_blob {
1160 if ($m->{mode_b} =~ /^120/) {
1161 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1163 blob_to_file($m->{sha1_b}, $m->{file_b});
1167 sub blob_to_symlink {
1168 my ($blob, $link) = @_;
1169 defined $link or croak "\$link not defined!\n";
1170 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1171 if (-l $link || -f _) {
1172 unlink $link or croak $!;
1175 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1176 symlink $dest, $link or croak $!;
1180 my ($blob, $file) = @_;
1181 defined $file or croak "\$file not defined!\n";
1182 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1183 if (-l $file || -f _) {
1184 unlink $file or croak $!;
1187 open my $blob_fh, '>', $file or croak "$!: $file\n";
1189 defined $pid or croak $!;
1192 open STDOUT, '>&', $blob_fh or croak $!;
1193 exec('git-cat-file','blob',$blob);
1198 close $blob_fh or croak $!;
1202 my $pid = open my $child, '-|';
1203 defined $pid or croak $!;
1205 exec(@_) or croak $?;
1207 my @ret = (<$child>);
1208 close $child or croak $?;
1209 die $? if $?; # just in case close didn't error out
1210 return wantarray ? @ret : join('',@ret);
1213 sub svn_compat_check {
1214 my @co_help = safe_qx(qw(svn co -h));
1215 unless (grep /ignore-externals/,@co_help) {
1216 print STDERR "W: Installed svn version does not support ",
1217 "--ignore-externals\n";
1218 $_no_ignore_ext = 1;
1220 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1221 $_svn_co_url_revs = 1;
1223 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1224 $_svn_pg_peg_revs = 1;
1227 # I really, really hope nobody hits this...
1228 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1230 W: The installed svn version does not support the --stop-on-copy flag in
1232 Lets hope the directory you're tracking is not a branch or tag
1233 and was never moved within the repository...
1239 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1240 # (and they won't honor URL@<rev> without -r<rev>, too!)
1241 sub svn_cmd_checkout {
1242 my ($url, $rev, $dir) = @_;
1243 my @cmd = ('svn','co', "-r$rev");
1244 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1245 $url .= "\@$rev" if $_svn_co_url_revs;
1246 sys(@cmd, $url, $dir);
1249 sub check_upgrade_needed {
1251 my $pid = open my $child, '-|';
1252 defined $pid or croak $!;
1255 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1257 my @ret = (<$child>);
1258 close $child or croak $?;
1259 die $? if $?; # just in case close didn't error out
1260 return wantarray ? @ret : join('',@ret);
1263 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1265 print STDERR "Please run: $0 rebuild --upgrade\n";
1270 # fills %tree_map with a reverse mapping of trees to commits. Useful
1271 # for finding parents to commit on.
1272 sub map_tree_joins {
1274 foreach my $br (@_branch_from) {
1275 my $pid = open my $pipe, '-|';
1276 defined $pid or croak $!;
1278 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1282 if (/^commit ($sha1)$/o) {
1285 # if we've seen a commit,
1286 # we've seen its parents
1287 last if $seen{$commit};
1288 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1289 unless (defined $tree) {
1290 die "Failed to parse commit $commit\n";
1292 push @{$tree_map{$tree}}, $commit;
1296 close $pipe; # we could be breaking the pipe early
1301 if (@_branch_from) {
1302 print STDERR '--branch|-b parameters are ignored when ',
1303 "--branch-all-refs|-B is passed\n";
1306 # don't worry about rev-list on non-commit objects/tags,
1307 # it shouldn't blow up if a ref is a blob or tree...
1308 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1311 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1313 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1314 while (<$authors>) {
1316 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1317 my ($user, $name, $email) = ($1, $2, $3);
1318 $users{$user} = [$name, $email];
1320 close $authors or croak $!;
1323 sub svn_propget_base {
1325 $f .= '@BASE' if $_svn_pg_peg_revs;
1326 return safe_qx(qw/svn propget/, $p, $f);
1329 sub migration_check {
1330 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1331 print "Upgrading repository...\n";
1332 unless (-d "$GIT_DIR/svn") {
1333 mkdir "$GIT_DIR/svn" or croak $!;
1335 print "Data from a previous version of git-svn exists, but\n\t",
1336 "$GIT_SVN_DIR\n\t(required for this version ",
1337 "($VERSION) of git-svn) does not.\n";
1339 foreach my $x (`git-rev-parse --symbolic --all`) {
1340 next unless $x =~ s#^refs/remotes/##;
1342 next unless -f "$GIT_DIR/$x/info/url";
1343 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1345 my $dn = dirname("$GIT_DIR/svn/$x");
1346 mkpath([$dn]) unless -d $dn;
1347 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1348 my ($url, $path) = repo_path_split($u);
1349 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
1350 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
1352 print "Done upgrading.\n";
1359 $svn_log hashref (as returned by svn_log_raw)
1361 fh => file handle of the log file,
1362 state => state of the log file parser (sep/msg/rev/msg_start...)
1365 $log_msg hashref as returned by next_log_entry($svn_log)
1367 msg => 'whitespace-formatted log entry
1368 ', # trailing newline is preserved
1369 revision => '8', # integer
1370 date => '2004-02-24T17:01:44.108345Z', # commit date
1371 author => 'committer name'
1375 @mods = array of diff-index line hashes, each element represents one line
1376 of diff-index output
1378 diff-index line ($m hash)
1380 mode_a => first column of diff-index output, no leading ':',
1381 mode_b => second column of diff-index output,
1382 sha1_b => sha1sum of the final blob,
1383 chg => change type [MCRADT],
1384 file_a => original file name of a file (iff chg is 'C' or 'R')
1385 file_b => new/current file name of a file (any chg)