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 read_repo_config(\%opts);
81 GetOptions(%opts, 'help|H|h' => \$_help,
82 'version|V' => \$_version,
83 'id|i=s' => \$GIT_SVN) or exit 1;
86 version() if $_version;
87 usage(1) unless defined $cmd;
89 load_authors() if $_authors;
90 load_all_refs() if $_branch_all_refs;
92 migration_check() unless $cmd eq 'init';
93 $cmd{$cmd}->[0]->(@ARGV);
96 ####################### primary functions ######################
98 my $exit = shift || 0;
99 my $fd = $exit ? \*STDERR : \*STDOUT;
101 git-svn - bidirectional operations between a single Subversion tree and git
102 Usage: $0 <command> [options] [arguments]\n
104 print $fd "Available commands:\n" unless $cmd;
106 foreach (sort keys %cmd) {
107 next if $cmd && $cmd ne $_;
108 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
109 foreach (keys %{$cmd{$_}->[2]}) {
110 # prints out arguments as they should be passed:
111 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
112 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
114 split /\|/,$_)," $x\n";
118 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
119 arbitrary identifier if you're tracking multiple SVN branches/repositories in
120 one git repository and want to keep them separate. See git-svn(1) for more
127 print "git-svn version $VERSION\n";
132 $SVN_URL = shift or undef;
135 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
137 check_upgrade_needed();
140 my $pid = open(my $rev_list,'-|');
141 defined $pid or croak $!;
143 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
146 while (<$rev_list>) {
149 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
150 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
151 next if (!@commit); # skip merges
152 my $id = $commit[$#commit];
153 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
155 if (!$rev || !$uuid || !$url) {
156 # some of the original repositories I made had
157 # indentifiers like this:
158 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
160 if (!$rev || !$uuid) {
161 croak "Unable to extract revision or UUID from ",
166 # if we merged or otherwise started elsewhere, this is
167 # how we break out of it
168 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
169 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
171 print "r$rev = $c\n";
172 unless (defined $latest) {
173 if (!$SVN_URL && !$url) {
174 croak "SVN repository location required: $url\n";
181 assert_revision_eq_or_unknown($rev, $c);
182 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
183 $newest_rev = $rev if ($rev > $newest_rev);
185 close $rev_list or croak $?;
186 if (!chdir $SVN_WC) {
187 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
188 chdir $SVN_WC or croak $!;
192 defined $pid or croak $!;
194 my @svn_up = qw(svn up);
195 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
196 sys(@svn_up,"-r$newest_rev");
197 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
199 exec('git-write-tree') or croak $!;
206 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
207 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
213 $SVN_URL = shift or die "SVN repository location required " .
214 "as a command-line argument\n";
215 unless (-d $GIT_DIR) {
223 check_upgrade_needed();
224 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
225 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
226 unless ($_revision) {
227 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
229 push @log_args, "-r$_revision";
230 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
232 my $svn_log = svn_log_raw(@log_args);
234 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
235 my $last_commit = undef;
236 unless (-d $SVN_WC) {
237 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
238 chdir $SVN_WC or croak $!;
240 $last_commit = git_commit($base, @parents);
241 assert_tree($last_commit);
243 chdir $SVN_WC or croak $!;
245 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
246 # looks like a user manually cp'd and svn switch'ed
247 unless ($last_commit) {
248 sys(qw/svn revert -R ./);
249 assert_svn_wc_clean($base->{revision});
250 $last_commit = git_commit($base, @parents);
251 assert_tree($last_commit);
254 my @svn_up = qw(svn up);
255 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
257 while (my $log_msg = next_log_entry($svn_log)) {
258 assert_tree($last_commit);
259 if ($last->{revision} >= $log_msg->{revision}) {
260 croak "Out of order: last >= current: ",
261 "$last->{revision} >= $log_msg->{revision}\n";
263 # Revert is needed for cases like:
264 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
265 # I can't seem to reproduce something like that on a test...
266 sys(qw/svn revert -R ./);
267 assert_svn_wc_clean($last->{revision});
268 sys(@svn_up,"-r$log_msg->{revision}");
269 $last_commit = git_commit($log_msg, $last_commit, @parents);
272 unless (-e "$GIT_DIR/refs/heads/master") {
273 sys(qw(git-update-ref refs/heads/master),$last_commit);
275 close $svn_log->{fh};
281 check_upgrade_needed();
282 if ($_stdin || !@commits) {
283 print "Reading from stdin...\n";
286 if (/\b($sha1_short)\b/o) {
287 unshift @commits, $1;
292 foreach my $c (@commits) {
293 chomp(my @tmp = safe_qx('git-rev-parse',$c));
294 if (scalar @tmp == 1) {
296 } elsif (scalar @tmp > 1) {
297 push @revs, reverse (safe_qx('git-rev-list',@tmp));
299 die "Failed to rev-parse $c\n";
304 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
305 my $info = svn_info('.');
306 my $fetched = fetch();
307 if ($info->{Revision} != $fetched->{revision}) {
308 print STDERR "There are new revisions that were fetched ",
309 "and need to be merged (or acknowledged) ",
310 "before committing.\n";
313 $info = svn_info('.');
315 my $svn_current_rev = $info->{'Last Changed Rev'};
316 foreach my $c (@revs) {
317 my $mods = svn_checkout_tree($svn_current_rev, $c);
318 if (scalar @$mods == 0) {
319 print "Skipping, no changes detected\n";
322 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
324 print "Done committing ",scalar @revs," revisions to SVN\n";
328 require File::Find or die $!;
329 my $exclude_file = "$GIT_DIR/info/exclude";
330 open my $fh, '<', $exclude_file or croak $!;
331 chomp(my @excludes = (<$fh>));
332 close $fh or croak $!;
334 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
335 chdir $SVN_WC or croak $!;
337 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
339 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
340 }}, no_chdir=>1},'.');
343 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
345 foreach my $i (sort keys %ign) {
346 print "\n# ",$i,"\n";
347 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
351 ########################### utility functions #########################
355 my $info = shift || svn_info('.');
356 $SVN_UUID = $info->{'Repository UUID'} or
357 croak "Repository UUID unreadable\n";
358 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
363 defined $pid or croak $!;
365 open my $null, '>', '/dev/null' or croak $!;
366 open STDERR, '>&', $null or croak $!;
367 open STDOUT, '>&', $null or croak $!;
374 sub repo_path_split {
375 my $full_url = shift;
376 $full_url =~ s#/+$##;
378 foreach (@repo_path_split_cache) {
379 if ($full_url =~ s#$_##) {
381 $full_url =~ s#^/+##;
382 return ($u, $full_url);
386 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
388 my @paths = split(m#/+#, $path);
390 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
391 my $n = shift @paths || last;
394 push @repo_path_split_cache, qr/^(\Q$url\E)/;
395 return ($url, $path);
399 defined $SVN_URL or croak "SVN repository location required\n";
400 unless (-d $GIT_DIR) {
401 croak "GIT_DIR=$GIT_DIR does not exist!\n";
403 mkpath([$GIT_SVN_DIR]);
404 mkpath(["$GIT_SVN_DIR/info"]);
406 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
408 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
409 print $fd '.svn',"\n";
410 close $fd or croak $!;
411 my ($url, $path) = repo_path_split($SVN_URL);
412 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
413 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
416 sub assert_svn_wc_clean {
418 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
419 my $lcr = svn_info('.')->{'Last Changed Rev'};
420 if ($svn_rev != $lcr) {
421 print STDERR "Checking for copy-tree ... ";
422 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
423 "-r$lcr:$svn_rev")));
425 croak "Nope! Expected r$svn_rev, got r$lcr\n";
427 print STDERR "OK!\n";
430 my @status = grep(!/^Performing status on external/,(`svn status`));
431 @status = grep(!/^\s*$/,@status);
432 if (scalar @status) {
433 print STDERR "Tree ($SVN_WC) is not clean:\n";
434 print STDERR $_ foreach @status;
441 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
442 chomp(my $type = `git-cat-file -t $treeish`);
444 while ($type eq 'tag') {
445 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
447 if ($type eq 'commit') {
448 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
449 ($expected) = ($expected =~ /^tree ($sha1)$/);
450 die "Unable to get tree from $treeish\n" unless $expected;
451 } elsif ($type eq 'tree') {
452 $expected = $treeish;
454 die "$treeish is a $type, expected tree, tag or commit\n";
457 my $old_index = $ENV{GIT_INDEX_FILE};
458 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
460 unlink $tmpindex or croak $!;
462 $ENV{GIT_INDEX_FILE} = $tmpindex;
464 chomp(my $tree = `git-write-tree`);
466 $ENV{GIT_INDEX_FILE} = $old_index;
468 delete $ENV{GIT_INDEX_FILE};
470 if ($tree ne $expected) {
471 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
476 sub parse_diff_tree {
482 chomp $_; # this gets rid of the trailing "\0"
483 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
484 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
485 push @mods, { mode_a => $1, mode_b => $2,
486 sha1_b => $3, chg => $4 };
487 if ($4 =~ /^(?:C|R)$/) {
492 } elsif ($state eq 'file_a') {
493 my $x = $mods[$#mods] or croak "Empty array\n";
494 if ($x->{chg} !~ /^(?:C|R)$/) {
495 croak "Error parsing $_, $x->{chg}\n";
499 } elsif ($state eq 'file_b') {
500 my $x = $mods[$#mods] or croak "Empty array\n";
501 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
502 croak "Error parsing $_, $x->{chg}\n";
504 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
505 croak "Error parsing $_, $x->{chg}\n";
510 croak "Error parsing $_\n";
513 close $diff_fh or croak $!;
518 sub svn_check_prop_executable {
520 return if -l $m->{file_b};
521 if ($m->{mode_b} =~ /755$/) {
522 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
523 if ($m->{mode_a} !~ /755$/) {
524 sys(qw(svn propset svn:executable 1), $m->{file_b});
526 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
527 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
528 sys(qw(svn propdel svn:executable), $m->{file_b});
529 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
530 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
534 sub svn_ensure_parent_path {
535 my $dir_b = dirname(shift);
536 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
537 mkpath([$dir_b]) unless (-d $dir_b);
538 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
541 sub precommit_check {
543 my (%rm_file, %rmdir_check, %added_check);
545 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
546 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
547 if ($m->{chg} eq 'R') {
548 if (-d $m->{file_b}) {
549 err_dir_to_file("$m->{file_a} => $m->{file_b}");
551 # dir/$file => dir/file/$file
552 my $dirname = dirname($m->{file_b});
553 while ($dirname ne File::Spec->curdir) {
554 if ($dirname ne $m->{file_a}) {
555 $dirname = dirname($dirname);
558 err_file_to_dir("$m->{file_a} => $m->{file_b}");
560 # baz/zzz => baz (baz is a file)
561 $dirname = dirname($m->{file_a});
562 while ($dirname ne File::Spec->curdir) {
563 if ($dirname ne $m->{file_b}) {
564 $dirname = dirname($dirname);
567 err_dir_to_file("$m->{file_a} => $m->{file_b}");
570 if ($m->{chg} =~ /^(D|R)$/) {
571 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
572 $rm_file{ $m->{$t} } = 1;
573 my $dirname = dirname( $m->{$t} );
574 my $basename = basename( $m->{$t} );
575 $rmdir_check{$dirname}->{$basename} = 1;
576 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
577 if (-d $m->{file_b}) {
578 err_dir_to_file($m->{file_b});
580 my $dirname = dirname( $m->{file_b} );
581 my $basename = basename( $m->{file_b} );
582 $added_check{$dirname}->{$basename} = 1;
583 while ($dirname ne File::Spec->curdir) {
584 if ($rm_file{$dirname}) {
585 err_file_to_dir($m->{file_b});
587 $dirname = dirname $dirname;
591 return (\%rmdir_check, \%added_check);
593 sub err_dir_to_file {
595 print STDERR "Node change from directory to file ",
596 "is not supported by Subversion: ",$file,"\n";
599 sub err_file_to_dir {
601 print STDERR "Node change from file to directory ",
602 "is not supported by Subversion: ",$file,"\n";
607 sub svn_checkout_tree {
608 my ($svn_rev, $treeish) = @_;
609 my $from = file_to_s("$REV_DIR/$svn_rev");
611 print "diff-tree $from $treeish\n";
612 my $pid = open my $diff_fh, '-|';
613 defined $pid or croak $!;
615 my @diff_tree = qw(git-diff-tree -z -r);
616 if ($_cp_similarity) {
617 push @diff_tree, "-C$_cp_similarity";
619 push @diff_tree, '-C';
621 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
622 push @diff_tree, "-l$_l" if defined $_l;
623 exec(@diff_tree, $from, $treeish) or croak $!;
625 my $mods = parse_diff_tree($diff_fh);
627 # git can do empty commits, but SVN doesn't allow it...
630 my ($rm, $add) = precommit_check($mods);
632 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
633 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
634 if ($m->{chg} eq 'C') {
635 svn_ensure_parent_path( $m->{file_b} );
636 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
637 apply_mod_line_blob($m);
638 svn_check_prop_executable($m);
639 } elsif ($m->{chg} eq 'D') {
640 sys(qw(svn rm --force), $m->{file_b});
641 } elsif ($m->{chg} eq 'R') {
642 svn_ensure_parent_path( $m->{file_b} );
643 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
644 apply_mod_line_blob($m);
645 svn_check_prop_executable($m);
646 } elsif ($m->{chg} eq 'M') {
647 apply_mod_line_blob($m);
648 svn_check_prop_executable($m);
649 } elsif ($m->{chg} eq 'T') {
650 sys(qw(svn rm --force),$m->{file_b});
651 apply_mod_line_blob($m);
652 sys(qw(svn add --force), $m->{file_b});
653 svn_check_prop_executable($m);
654 } elsif ($m->{chg} eq 'A') {
655 svn_ensure_parent_path( $m->{file_b} );
656 apply_mod_line_blob($m);
657 sys(qw(svn add --force), $m->{file_b});
658 svn_check_prop_executable($m);
660 croak "Invalid chg: $m->{chg}\n";
664 assert_tree($treeish);
665 if ($_rmdir) { # remove empty directories
666 handle_rmdir($rm, $add);
668 assert_tree($treeish);
672 # svn ls doesn't work with respect to the current working tree, but what's
673 # in the repository. There's not even an option for it... *sigh*
674 # (added files don't show up and removed files remain in the ls listing)
676 my ($dir, $rm, $add) = @_;
677 chomp(my @ls = safe_qx('svn','ls',$dir));
680 s#/$##; # trailing slashes are evil
681 push @ret, $_ unless $rm->{$dir}->{$_};
683 if (exists $add->{$dir}) {
684 push @ret, keys %{$add->{$dir}};
692 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
693 my $ls = svn_ls_current($dir, $rm, $add);
694 next if (scalar @$ls);
695 sys(qw(svn rm --force),$dir);
697 my $dn = dirname $dir;
698 $rm->{ $dn }->{ basename $dir } = 1;
699 $ls = svn_ls_current($dn, $rm, $add);
700 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
701 sys(qw(svn rm --force),$dn);
704 $rm->{ $dn }->{ $dir } = 1;
705 $ls = svn_ls_current($dn, $rm, $add);
710 sub svn_commit_tree {
711 my ($svn_rev, $commit) = @_;
712 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
713 my %log_msg = ( msg => '' );
714 open my $msg, '>', $commit_msg or croak $!;
716 chomp(my $type = `git-cat-file -t $commit`);
717 if ($type eq 'commit') {
718 my $pid = open my $msg_fh, '-|';
719 defined $pid or croak $!;
722 exec(qw(git-cat-file commit), $commit) or croak $!;
727 $in_msg = 1 if (/^\s*$/);
728 } elsif (/^git-svn-id: /) {
729 # skip this, we regenerate the correct one
730 # on re-fetch anyways
732 print $msg $_ or croak $!;
735 close $msg_fh or croak $!;
737 close $msg or croak $!;
739 if ($_edit || ($type eq 'tree')) {
740 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
741 system($editor, $commit_msg);
744 # file_to_s removes all trailing newlines, so just use chomp() here:
745 open $msg, '<', $commit_msg or croak $!;
746 { local $/; chomp($log_msg{msg} = <$msg>); }
747 close $msg or croak $!;
749 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
750 print "Committing $commit: $oneline\n";
752 if (defined $LC_ALL) {
753 $ENV{LC_ALL} = $LC_ALL;
757 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
760 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
761 if (!defined $committed) {
762 my $out = join("\n",@ci_output);
763 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
764 $out, "\n\nAssuming English locale...";
765 ($committed) = ($out =~ /^Committed revision \d+\./sm);
766 defined $committed or die " FAILED!\n",
767 "Commit output failed to parse committed revision!\n",
768 print STDERR " OK\n";
771 my @svn_up = qw(svn up);
772 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
773 if ($committed == ($svn_rev + 1)) {
774 push @svn_up, "-r$committed";
776 my $info = svn_info('.');
777 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
778 if ($info->{'Last Changed Rev'} != $committed) {
779 croak "$info->{'Last Changed Rev'} != $committed\n"
781 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
782 /(\d{4})\-(\d\d)\-(\d\d)\s
783 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
784 or croak "Failed to parse date: $date\n";
785 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
786 $log_msg{author} = $info->{'Last Changed Author'};
787 $log_msg{revision} = $committed;
788 $log_msg{msg} .= "\n";
789 my $parent = file_to_s("$REV_DIR/$svn_rev");
790 git_commit(\%log_msg, $parent, $commit);
794 push @svn_up, "-r$svn_rev";
796 return fetch("$committed=$commit")->{revision};
799 # read the entire log into a temporary file (which is removed ASAP)
800 # and store the file handle + parser state
803 my $log_fh = IO::File->new_tmpfile or croak $!;
805 defined $pid or croak $!;
807 open STDOUT, '>&', $log_fh or croak $!;
808 exec (qw(svn log), @log_args) or croak $!
812 seek $log_fh, 0, 0 or croak $!;
813 return { state => 'sep', fh => $log_fh };
817 my $log = shift; # retval of svn_log_raw()
824 if ($log->{state} eq 'msg') {
826 $ret->{msg} .= $_."\n";
827 unless(--$ret->{lines}) {
828 $log->{state} = 'sep';
831 croak "Log parse error at: $_\n",
837 if ($log->{state} ne 'sep') {
838 croak "Log parse error at: $_\n",
839 "state: $log->{state}\n",
843 $log->{state} = 'rev';
845 # if we have an empty log message, put something there:
847 $ret->{msg} ||= "\n";
848 delete $ret->{lines};
853 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
855 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
856 ($lines) = ($lines =~ /(\d+)/);
857 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
858 /(\d{4})\-(\d\d)\-(\d\d)\s
859 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
860 or croak "Failed to parse date: $date\n";
861 $ret = { revision => $rev,
862 date => "$tz $Y-$m-$d $H:$M:$S",
866 if (defined $_authors && ! defined $users{$author}) {
867 die "Author: $author not defined in ",
870 $log->{state} = 'msg_start';
873 # skip the first blank line of the message:
874 if ($log->{state} eq 'msg_start' && /^$/) {
875 $log->{state} = 'msg';
876 } elsif ($log->{state} eq 'msg') {
878 $ret->{msg} .= $_."\n";
879 unless (--$ret->{lines}) {
880 $log->{state} = 'sep';
883 croak "Log parse error at: $_\n",
884 $ret->{revision},"\n";
892 my $url = shift || $SVN_URL;
894 my $pid = open my $info_fh, '-|';
895 defined $pid or croak $!;
898 exec(qw(svn info),$url) or croak $!;
902 # only single-lines seem to exist in svn info output
905 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
907 push @{$ret->{-order}}, $1;
910 close $info_fh or croak $!;
914 sub sys { system(@_) == 0 or croak $? }
917 my ($from, $to) = @_;
918 my $es = svn_propget_base('svn:eol-style', $to);
919 open my $rfd, '<', $from or croak $!;
920 binmode $rfd or croak $!;
921 open my $wfd, '>', $to or croak $!;
922 binmode $wfd or croak $!;
924 my $eol = $EOL{$es} or undef;
929 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
932 if ($buf =~ /\015$/) {
934 defined($r = sysread($rfd,$c,1)) or croak $!;
935 $buf .= $c if $r > 0;
937 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
940 for ($w = 0; $w < $r; $w += $t) {
941 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
947 sub do_update_index {
948 my ($z_cmd, $cmd, $no_text_base) = @_;
950 my $z = open my $p, '-|';
951 defined $z or croak $!;
952 unless ($z) { exec @$z_cmd or croak $! }
954 my $pid = open my $ui, '|-';
955 defined $pid or croak $!;
957 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
960 while (my $x = <$p>) {
962 if (!$no_text_base && lstat $x && ! -l _ &&
963 svn_propget_base('svn:keywords', $x)) {
964 my $mode = -x _ ? 0755 : 0644;
965 my ($v,$d,$f) = File::Spec->splitpath($x);
966 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
967 'text-base',"$f.svn-base");
970 $tb = File::Spec->catfile($d, '.svn',
971 'text-base',"$f.svn-base");
974 unlink $x or croak $!;
976 chmod(($mode &~ umask), $x) or croak $!;
980 close $ui or croak $!;
984 my $no_text_base = shift;
985 do_update_index([qw/git-diff-files --name-only -z/],
988 do_update_index([qw/git-ls-files -z --others/,
989 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
995 my ($str, $file, $mode) = @_;
996 open my $fd,'>',$file or croak $!;
997 print $fd $str,"\n" or croak $!;
998 close $fd or croak $!;
999 chmod ($mode &~ umask, $file) if (defined $mode);
1004 open my $fd,'<',$file or croak "$!: file: $file\n";
1007 close $fd or croak $!;
1012 sub assert_revision_unknown {
1014 if (-f "$REV_DIR/$revno") {
1015 croak "$REV_DIR/$revno already exists! ",
1016 "Why are we refetching it?";
1022 my @x = safe_qx('git-cat-file','commit',$x);
1023 my @y = safe_qx('git-cat-file','commit',$y);
1024 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1025 || $y[0] !~ /^tree $sha1\n$/) {
1026 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1032 sub assert_revision_eq_or_unknown {
1033 my ($revno, $commit) = @_;
1034 if (-f "$REV_DIR/$revno") {
1035 my $current = file_to_s("$REV_DIR/$revno");
1036 if (($commit ne $current) && !trees_eq($commit, $current)) {
1037 croak "$REV_DIR/$revno already exists!\n",
1038 "current: $current\nexpected: $commit\n";
1045 my ($log_msg, @parents) = @_;
1046 assert_revision_unknown($log_msg->{revision});
1047 my $out_fh = IO::File->new_tmpfile or croak $!;
1049 map_tree_joins() if (@_branch_from && !%tree_map);
1051 # commit parents can be conditionally bound to a particular
1052 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1054 foreach my $p (@parents) {
1055 next unless defined $p;
1056 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1057 if ($1 == $log_msg->{revision}) {
1058 push @exec_parents, $2;
1061 push @exec_parents, $p if $p =~ /$sha1_short/o;
1066 defined $pid or croak $!;
1068 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1070 chomp(my $tree = `git-write-tree`);
1072 if (exists $tree_map{$tree}) {
1073 my %seen_parent = map { $_ => 1 } @exec_parents;
1074 foreach (@{$tree_map{$tree}}) {
1075 # MAXPARENT is defined to 16 in commit-tree.c:
1076 if ($seen_parent{$_} || @exec_parents > 16) {
1079 push @exec_parents, $_;
1080 $seen_parent{$_} = 1;
1083 my $msg_fh = IO::File->new_tmpfile or croak $!;
1084 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1085 "$SVN_URL\@$log_msg->{revision}",
1086 " $SVN_UUID\n" or croak $!;
1087 $msg_fh->flush == 0 or croak $!;
1088 seek $msg_fh, 0, 0 or croak $!;
1090 set_commit_env($log_msg);
1092 my @exec = ('git-commit-tree',$tree);
1093 push @exec, '-p', $_ foreach @exec_parents;
1094 open STDIN, '<&', $msg_fh or croak $!;
1095 open STDOUT, '>&', $out_fh or croak $!;
1096 exec @exec or croak $!;
1101 $out_fh->flush == 0 or croak $!;
1102 seek $out_fh, 0, 0 or croak $!;
1103 chomp(my $commit = do { local $/; <$out_fh> });
1104 if ($commit !~ /^$sha1$/o) {
1105 croak "Failed to commit, invalid sha1: $commit\n";
1107 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1108 if (my $primary_parent = shift @exec_parents) {
1110 defined $pid or croak $!;
1114 exec 'git-rev-parse','--verify',
1115 "refs/remotes/$GIT_SVN^0" or croak $!;
1118 push @update_ref, $primary_parent unless $?;
1121 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
1122 print "r$log_msg->{revision} = $commit\n";
1126 sub set_commit_env {
1128 my $author = $log_msg->{author};
1129 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1130 : ($author,"$author\@$SVN_UUID");
1131 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1132 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1133 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1136 sub apply_mod_line_blob {
1138 if ($m->{mode_b} =~ /^120/) {
1139 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1141 blob_to_file($m->{sha1_b}, $m->{file_b});
1145 sub blob_to_symlink {
1146 my ($blob, $link) = @_;
1147 defined $link or croak "\$link not defined!\n";
1148 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1149 if (-l $link || -f _) {
1150 unlink $link or croak $!;
1153 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1154 symlink $dest, $link or croak $!;
1158 my ($blob, $file) = @_;
1159 defined $file or croak "\$file not defined!\n";
1160 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1161 if (-l $file || -f _) {
1162 unlink $file or croak $!;
1165 open my $blob_fh, '>', $file or croak "$!: $file\n";
1167 defined $pid or croak $!;
1170 open STDOUT, '>&', $blob_fh or croak $!;
1171 exec('git-cat-file','blob',$blob) or croak $!;
1176 close $blob_fh or croak $!;
1180 my $pid = open my $child, '-|';
1181 defined $pid or croak $!;
1183 exec(@_) or croak $!;
1185 my @ret = (<$child>);
1186 close $child or croak $?;
1187 die $? if $?; # just in case close didn't error out
1188 return wantarray ? @ret : join('',@ret);
1191 sub svn_compat_check {
1192 my @co_help = safe_qx(qw(svn co -h));
1193 unless (grep /ignore-externals/,@co_help) {
1194 print STDERR "W: Installed svn version does not support ",
1195 "--ignore-externals\n";
1196 $_no_ignore_ext = 1;
1198 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1199 $_svn_co_url_revs = 1;
1201 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1202 $_svn_pg_peg_revs = 1;
1205 # I really, really hope nobody hits this...
1206 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1208 W: The installed svn version does not support the --stop-on-copy flag in
1210 Lets hope the directory you're tracking is not a branch or tag
1211 and was never moved within the repository...
1217 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1218 # (and they won't honor URL@<rev> without -r<rev>, too!)
1219 sub svn_cmd_checkout {
1220 my ($url, $rev, $dir) = @_;
1221 my @cmd = ('svn','co', "-r$rev");
1222 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1223 $url .= "\@$rev" if $_svn_co_url_revs;
1224 sys(@cmd, $url, $dir);
1227 sub check_upgrade_needed {
1229 my $pid = open my $child, '-|';
1230 defined $pid or croak $!;
1233 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1235 my @ret = (<$child>);
1236 close $child or croak $?;
1237 die $? if $?; # just in case close didn't error out
1238 return wantarray ? @ret : join('',@ret);
1241 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1243 print STDERR "Please run: $0 rebuild --upgrade\n";
1248 # fills %tree_map with a reverse mapping of trees to commits. Useful
1249 # for finding parents to commit on.
1250 sub map_tree_joins {
1252 foreach my $br (@_branch_from) {
1253 my $pid = open my $pipe, '-|';
1254 defined $pid or croak $!;
1256 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1260 if (/^commit ($sha1)$/o) {
1263 # if we've seen a commit,
1264 # we've seen its parents
1265 last if $seen{$commit};
1266 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1267 unless (defined $tree) {
1268 die "Failed to parse commit $commit\n";
1270 push @{$tree_map{$tree}}, $commit;
1274 close $pipe; # we could be breaking the pipe early
1279 if (@_branch_from) {
1280 print STDERR '--branch|-b parameters are ignored when ',
1281 "--branch-all-refs|-B is passed\n";
1284 # don't worry about rev-list on non-commit objects/tags,
1285 # it shouldn't blow up if a ref is a blob or tree...
1286 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1289 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1291 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1292 while (<$authors>) {
1294 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1295 my ($user, $name, $email) = ($1, $2, $3);
1296 $users{$user} = [$name, $email];
1298 close $authors or croak $!;
1301 sub svn_propget_base {
1303 $f .= '@BASE' if $_svn_pg_peg_revs;
1304 return safe_qx(qw/svn propget/, $p, $f);
1307 sub migration_check {
1308 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1309 print "Upgrading repository...\n";
1310 unless (-d "$GIT_DIR/svn") {
1311 mkdir "$GIT_DIR/svn" or croak $!;
1313 print "Data from a previous version of git-svn exists, but\n\t",
1314 "$GIT_SVN_DIR\n\t(required for this version ",
1315 "($VERSION) of git-svn) does not.\n";
1317 foreach my $x (`git-rev-parse --symbolic --all`) {
1318 next unless $x =~ s#^refs/remotes/##;
1320 next unless -f "$GIT_DIR/$x/info/url";
1321 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1323 my $dn = dirname("$GIT_DIR/svn/$x");
1324 mkpath([$dn]) unless -d $dn;
1325 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1326 my ($url, $path) = repo_path_split($u);
1327 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
1328 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
1330 print "Done upgrading.\n";
1334 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1335 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1336 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1338 $REV_DIR = "$GIT_SVN_DIR/revs";
1339 $SVN_WC = "$GIT_SVN_DIR/tree";
1342 # convert GetOpt::Long specs for use by git-repo-config
1343 sub read_repo_config {
1344 return unless -d $GIT_DIR;
1346 foreach my $o (keys %$opts) {
1347 my $v = $opts->{$o};
1348 my ($key) = ($o =~ /^([a-z\-]+)/);
1350 my $arg = 'git-repo-config';
1351 $arg .= ' --int' if ($o =~ /[:=]i$/);
1352 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1353 if (ref $v eq 'ARRAY') {
1354 chomp(my @tmp = `$arg --get-all svn.$key`);
1357 chomp(my $tmp = `$arg --get svn.$key`);
1358 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
1369 $svn_log hashref (as returned by svn_log_raw)
1371 fh => file handle of the log file,
1372 state => state of the log file parser (sep/msg/rev/msg_start...)
1375 $log_msg hashref as returned by next_log_entry($svn_log)
1377 msg => 'whitespace-formatted log entry
1378 ', # trailing newline is preserved
1379 revision => '8', # integer
1380 date => '2004-02-24T17:01:44.108345Z', # commit date
1381 author => 'committer name'
1385 @mods = array of diff-index line hashes, each element represents one line
1386 of diff-index output
1388 diff-index line ($m hash)
1390 mode_a => first column of diff-index output, no leading ':',
1391 mode_b => second column of diff-index output,
1392 sha1_b => sha1sum of the final blob,
1393 chg => change type [MCRADT],
1394 file_a => original file name of a file (iff chg is 'C' or 'R')
1395 file_b => new/current file name of a file (any chg)