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,
39 $_version, $_upgrade, $_authors, $_branch_all_refs);
40 my (@_branch_from, %tree_map, %users);
41 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
42 my @repo_path_split_cache;
44 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
45 'branch|b=s' => \@_branch_from,
46 'branch-all-refs|B' => \$_branch_all_refs,
47 'authors-file|A=s' => \$_authors,
48 'repack:i' => \$_repack,
49 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
51 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
52 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
55 fetch => [ \&fetch, "Download new revisions from SVN",
56 { 'revision|r=s' => \$_revision, %fc_opts } ],
57 init => [ \&init, "Initialize a repo for tracking" .
58 " (requires URL argument)",
59 { 'template=s' => \$_template,
60 'shared' => \$_shared } ],
61 commit => [ \&commit, "Commit git revisions to SVN",
62 { 'stdin|' => \$_stdin,
65 'find-copies-harder' => \$_find_copies_harder,
67 'copy-similarity|C=i'=> \$_cp_similarity,
70 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
71 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
72 { 'no-ignore-externals' => \$_no_ignore_ext,
73 'upgrade' => \$_upgrade } ],
76 for (my $i = 0; $i < @ARGV; $i++) {
77 if (defined $cmd{$ARGV[$i]}) {
84 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
86 read_repo_config(\%opts);
87 GetOptions(%opts, 'help|H|h' => \$_help,
88 'version|V' => \$_version,
89 'id|i=s' => \$GIT_SVN) or exit 1;
93 version() if $_version;
94 usage(1) unless defined $cmd;
96 load_authors() if $_authors;
97 load_all_refs() if $_branch_all_refs;
99 migration_check() unless $cmd eq 'init';
100 $cmd{$cmd}->[0]->(@ARGV);
103 ####################### primary functions ######################
105 my $exit = shift || 0;
106 my $fd = $exit ? \*STDERR : \*STDOUT;
108 git-svn - bidirectional operations between a single Subversion tree and git
109 Usage: $0 <command> [options] [arguments]\n
111 print $fd "Available commands:\n" unless $cmd;
113 foreach (sort keys %cmd) {
114 next if $cmd && $cmd ne $_;
115 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
116 foreach (keys %{$cmd{$_}->[2]}) {
117 # prints out arguments as they should be passed:
118 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
119 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
121 split /\|/,$_)," $x\n";
125 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
126 arbitrary identifier if you're tracking multiple SVN branches/repositories in
127 one git repository and want to keep them separate. See git-svn(1) for more
134 print "git-svn version $VERSION\n";
139 $SVN_URL = shift or undef;
142 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
144 check_upgrade_needed();
147 my $pid = open(my $rev_list,'-|');
148 defined $pid or croak $!;
150 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
153 while (<$rev_list>) {
156 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
157 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
158 next if (!@commit); # skip merges
159 my $id = $commit[$#commit];
160 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
162 if (!$rev || !$uuid || !$url) {
163 # some of the original repositories I made had
164 # indentifiers like this:
165 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
167 if (!$rev || !$uuid) {
168 croak "Unable to extract revision or UUID from ",
173 # if we merged or otherwise started elsewhere, this is
174 # how we break out of it
175 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
176 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
178 print "r$rev = $c\n";
179 unless (defined $latest) {
180 if (!$SVN_URL && !$url) {
181 croak "SVN repository location required: $url\n";
188 assert_revision_eq_or_unknown($rev, $c);
189 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
190 $newest_rev = $rev if ($rev > $newest_rev);
192 close $rev_list or croak $?;
193 if (!chdir $SVN_WC) {
194 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
195 chdir $SVN_WC or croak $!;
199 defined $pid or croak $!;
201 my @svn_up = qw(svn up);
202 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
203 sys(@svn_up,"-r$newest_rev");
204 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
206 exec('git-write-tree') or croak $!;
213 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
214 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
220 $SVN_URL = shift or die "SVN repository location required " .
221 "as a command-line argument\n";
222 unless (-d $GIT_DIR) {
223 my @init_db = ('git-init-db');
224 push @init_db, "--template=$_template" if defined $_template;
225 push @init_db, "--shared" if defined $_shared;
233 check_upgrade_needed();
234 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
235 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
236 unless ($_revision) {
237 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
239 push @log_args, "-r$_revision";
240 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
242 my $svn_log = svn_log_raw(@log_args);
244 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
245 my $last_commit = undef;
246 unless (-d $SVN_WC) {
247 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
248 chdir $SVN_WC or croak $!;
250 $last_commit = git_commit($base, @parents);
251 assert_tree($last_commit);
253 chdir $SVN_WC or croak $!;
255 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
256 # looks like a user manually cp'd and svn switch'ed
257 unless ($last_commit) {
258 sys(qw/svn revert -R ./);
259 assert_svn_wc_clean($base->{revision});
260 $last_commit = git_commit($base, @parents);
261 assert_tree($last_commit);
264 my @svn_up = qw(svn up);
265 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
267 while (my $log_msg = next_log_entry($svn_log)) {
268 assert_tree($last_commit);
269 if ($last->{revision} >= $log_msg->{revision}) {
270 croak "Out of order: last >= current: ",
271 "$last->{revision} >= $log_msg->{revision}\n";
273 # Revert is needed for cases like:
274 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
275 # I can't seem to reproduce something like that on a test...
276 sys(qw/svn revert -R ./);
277 assert_svn_wc_clean($last->{revision});
278 sys(@svn_up,"-r$log_msg->{revision}");
279 $last_commit = git_commit($log_msg, $last_commit, @parents);
282 unless (-e "$GIT_DIR/refs/heads/master") {
283 sys(qw(git-update-ref refs/heads/master),$last_commit);
285 close $svn_log->{fh};
291 check_upgrade_needed();
292 if ($_stdin || !@commits) {
293 print "Reading from stdin...\n";
296 if (/\b($sha1_short)\b/o) {
297 unshift @commits, $1;
302 foreach my $c (@commits) {
303 chomp(my @tmp = safe_qx('git-rev-parse',$c));
304 if (scalar @tmp == 1) {
306 } elsif (scalar @tmp > 1) {
307 push @revs, reverse (safe_qx('git-rev-list',@tmp));
309 die "Failed to rev-parse $c\n";
314 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
315 my $info = svn_info('.');
316 my $fetched = fetch();
317 if ($info->{Revision} != $fetched->{revision}) {
318 print STDERR "There are new revisions that were fetched ",
319 "and need to be merged (or acknowledged) ",
320 "before committing.\n";
323 $info = svn_info('.');
325 my $svn_current_rev = $info->{'Last Changed Rev'};
326 foreach my $c (@revs) {
327 my $mods = svn_checkout_tree($svn_current_rev, $c);
328 if (scalar @$mods == 0) {
329 print "Skipping, no changes detected\n";
332 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
334 print "Done committing ",scalar @revs," revisions to SVN\n";
338 require File::Find or die $!;
339 my $exclude_file = "$GIT_DIR/info/exclude";
340 open my $fh, '<', $exclude_file or croak $!;
341 chomp(my @excludes = (<$fh>));
342 close $fh or croak $!;
344 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
345 chdir $SVN_WC or croak $!;
347 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
349 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
350 }}, no_chdir=>1},'.');
353 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
355 foreach my $i (sort keys %ign) {
356 print "\n# ",$i,"\n";
357 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
361 ########################### utility functions #########################
365 my $info = shift || svn_info('.');
366 $SVN_UUID = $info->{'Repository UUID'} or
367 croak "Repository UUID unreadable\n";
368 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
373 defined $pid or croak $!;
375 open my $null, '>', '/dev/null' or croak $!;
376 open STDERR, '>&', $null or croak $!;
377 open STDOUT, '>&', $null or croak $!;
384 sub repo_path_split {
385 my $full_url = shift;
386 $full_url =~ s#/+$##;
388 foreach (@repo_path_split_cache) {
389 if ($full_url =~ s#$_##) {
391 $full_url =~ s#^/+##;
392 return ($u, $full_url);
396 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
398 my @paths = split(m#/+#, $path);
400 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
401 my $n = shift @paths || last;
404 push @repo_path_split_cache, qr/^(\Q$url\E)/;
405 return ($url, $path);
409 defined $SVN_URL or croak "SVN repository location required\n";
410 unless (-d $GIT_DIR) {
411 croak "GIT_DIR=$GIT_DIR does not exist!\n";
413 mkpath([$GIT_SVN_DIR]);
414 mkpath(["$GIT_SVN_DIR/info"]);
416 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
418 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
419 print $fd '.svn',"\n";
420 close $fd or croak $!;
421 my ($url, $path) = repo_path_split($SVN_URL);
422 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
423 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
426 sub assert_svn_wc_clean {
428 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
429 my $lcr = svn_info('.')->{'Last Changed Rev'};
430 if ($svn_rev != $lcr) {
431 print STDERR "Checking for copy-tree ... ";
432 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
433 "-r$lcr:$svn_rev")));
435 croak "Nope! Expected r$svn_rev, got r$lcr\n";
437 print STDERR "OK!\n";
440 my @status = grep(!/^Performing status on external/,(`svn status`));
441 @status = grep(!/^\s*$/,@status);
442 if (scalar @status) {
443 print STDERR "Tree ($SVN_WC) is not clean:\n";
444 print STDERR $_ foreach @status;
451 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
452 chomp(my $type = `git-cat-file -t $treeish`);
454 while ($type eq 'tag') {
455 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
457 if ($type eq 'commit') {
458 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
459 ($expected) = ($expected =~ /^tree ($sha1)$/);
460 die "Unable to get tree from $treeish\n" unless $expected;
461 } elsif ($type eq 'tree') {
462 $expected = $treeish;
464 die "$treeish is a $type, expected tree, tag or commit\n";
467 my $old_index = $ENV{GIT_INDEX_FILE};
468 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
470 unlink $tmpindex or croak $!;
472 $ENV{GIT_INDEX_FILE} = $tmpindex;
474 chomp(my $tree = `git-write-tree`);
476 $ENV{GIT_INDEX_FILE} = $old_index;
478 delete $ENV{GIT_INDEX_FILE};
480 if ($tree ne $expected) {
481 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
486 sub parse_diff_tree {
492 chomp $_; # this gets rid of the trailing "\0"
493 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
494 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
495 push @mods, { mode_a => $1, mode_b => $2,
496 sha1_b => $3, chg => $4 };
497 if ($4 =~ /^(?:C|R)$/) {
502 } elsif ($state eq 'file_a') {
503 my $x = $mods[$#mods] or croak "Empty array\n";
504 if ($x->{chg} !~ /^(?:C|R)$/) {
505 croak "Error parsing $_, $x->{chg}\n";
509 } elsif ($state eq 'file_b') {
510 my $x = $mods[$#mods] or croak "Empty array\n";
511 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
512 croak "Error parsing $_, $x->{chg}\n";
514 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
515 croak "Error parsing $_, $x->{chg}\n";
520 croak "Error parsing $_\n";
523 close $diff_fh or croak $!;
528 sub svn_check_prop_executable {
530 return if -l $m->{file_b};
531 if ($m->{mode_b} =~ /755$/) {
532 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
533 if ($m->{mode_a} !~ /755$/) {
534 sys(qw(svn propset svn:executable 1), $m->{file_b});
536 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
537 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
538 sys(qw(svn propdel svn:executable), $m->{file_b});
539 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
540 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
544 sub svn_ensure_parent_path {
545 my $dir_b = dirname(shift);
546 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
547 mkpath([$dir_b]) unless (-d $dir_b);
548 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
551 sub precommit_check {
553 my (%rm_file, %rmdir_check, %added_check);
555 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
556 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
557 if ($m->{chg} eq 'R') {
558 if (-d $m->{file_b}) {
559 err_dir_to_file("$m->{file_a} => $m->{file_b}");
561 # dir/$file => dir/file/$file
562 my $dirname = dirname($m->{file_b});
563 while ($dirname ne File::Spec->curdir) {
564 if ($dirname ne $m->{file_a}) {
565 $dirname = dirname($dirname);
568 err_file_to_dir("$m->{file_a} => $m->{file_b}");
570 # baz/zzz => baz (baz is a file)
571 $dirname = dirname($m->{file_a});
572 while ($dirname ne File::Spec->curdir) {
573 if ($dirname ne $m->{file_b}) {
574 $dirname = dirname($dirname);
577 err_dir_to_file("$m->{file_a} => $m->{file_b}");
580 if ($m->{chg} =~ /^(D|R)$/) {
581 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
582 $rm_file{ $m->{$t} } = 1;
583 my $dirname = dirname( $m->{$t} );
584 my $basename = basename( $m->{$t} );
585 $rmdir_check{$dirname}->{$basename} = 1;
586 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
587 if (-d $m->{file_b}) {
588 err_dir_to_file($m->{file_b});
590 my $dirname = dirname( $m->{file_b} );
591 my $basename = basename( $m->{file_b} );
592 $added_check{$dirname}->{$basename} = 1;
593 while ($dirname ne File::Spec->curdir) {
594 if ($rm_file{$dirname}) {
595 err_file_to_dir($m->{file_b});
597 $dirname = dirname $dirname;
601 return (\%rmdir_check, \%added_check);
603 sub err_dir_to_file {
605 print STDERR "Node change from directory to file ",
606 "is not supported by Subversion: ",$file,"\n";
609 sub err_file_to_dir {
611 print STDERR "Node change from file to directory ",
612 "is not supported by Subversion: ",$file,"\n";
617 sub svn_checkout_tree {
618 my ($svn_rev, $treeish) = @_;
619 my $from = file_to_s("$REV_DIR/$svn_rev");
621 print "diff-tree $from $treeish\n";
622 my $pid = open my $diff_fh, '-|';
623 defined $pid or croak $!;
625 my @diff_tree = qw(git-diff-tree -z -r);
626 if ($_cp_similarity) {
627 push @diff_tree, "-C$_cp_similarity";
629 push @diff_tree, '-C';
631 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
632 push @diff_tree, "-l$_l" if defined $_l;
633 exec(@diff_tree, $from, $treeish) or croak $!;
635 my $mods = parse_diff_tree($diff_fh);
637 # git can do empty commits, but SVN doesn't allow it...
640 my ($rm, $add) = precommit_check($mods);
642 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
643 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
644 if ($m->{chg} eq 'C') {
645 svn_ensure_parent_path( $m->{file_b} );
646 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
647 apply_mod_line_blob($m);
648 svn_check_prop_executable($m);
649 } elsif ($m->{chg} eq 'D') {
650 sys(qw(svn rm --force), $m->{file_b});
651 } elsif ($m->{chg} eq 'R') {
652 svn_ensure_parent_path( $m->{file_b} );
653 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
654 apply_mod_line_blob($m);
655 svn_check_prop_executable($m);
656 } elsif ($m->{chg} eq 'M') {
657 apply_mod_line_blob($m);
658 svn_check_prop_executable($m);
659 } elsif ($m->{chg} eq 'T') {
660 sys(qw(svn rm --force),$m->{file_b});
661 apply_mod_line_blob($m);
662 sys(qw(svn add --force), $m->{file_b});
663 svn_check_prop_executable($m);
664 } elsif ($m->{chg} eq 'A') {
665 svn_ensure_parent_path( $m->{file_b} );
666 apply_mod_line_blob($m);
667 sys(qw(svn add --force), $m->{file_b});
668 svn_check_prop_executable($m);
670 croak "Invalid chg: $m->{chg}\n";
674 assert_tree($treeish);
675 if ($_rmdir) { # remove empty directories
676 handle_rmdir($rm, $add);
678 assert_tree($treeish);
682 # svn ls doesn't work with respect to the current working tree, but what's
683 # in the repository. There's not even an option for it... *sigh*
684 # (added files don't show up and removed files remain in the ls listing)
686 my ($dir, $rm, $add) = @_;
687 chomp(my @ls = safe_qx('svn','ls',$dir));
690 s#/$##; # trailing slashes are evil
691 push @ret, $_ unless $rm->{$dir}->{$_};
693 if (exists $add->{$dir}) {
694 push @ret, keys %{$add->{$dir}};
702 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
703 my $ls = svn_ls_current($dir, $rm, $add);
704 next if (scalar @$ls);
705 sys(qw(svn rm --force),$dir);
707 my $dn = dirname $dir;
708 $rm->{ $dn }->{ basename $dir } = 1;
709 $ls = svn_ls_current($dn, $rm, $add);
710 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
711 sys(qw(svn rm --force),$dn);
714 $rm->{ $dn }->{ $dir } = 1;
715 $ls = svn_ls_current($dn, $rm, $add);
720 sub svn_commit_tree {
721 my ($svn_rev, $commit) = @_;
722 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
723 my %log_msg = ( msg => '' );
724 open my $msg, '>', $commit_msg or croak $!;
726 chomp(my $type = `git-cat-file -t $commit`);
727 if ($type eq 'commit') {
728 my $pid = open my $msg_fh, '-|';
729 defined $pid or croak $!;
732 exec(qw(git-cat-file commit), $commit) or croak $!;
737 $in_msg = 1 if (/^\s*$/);
738 } elsif (/^git-svn-id: /) {
739 # skip this, we regenerate the correct one
740 # on re-fetch anyways
742 print $msg $_ or croak $!;
745 close $msg_fh or croak $!;
747 close $msg or croak $!;
749 if ($_edit || ($type eq 'tree')) {
750 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
751 system($editor, $commit_msg);
754 # file_to_s removes all trailing newlines, so just use chomp() here:
755 open $msg, '<', $commit_msg or croak $!;
756 { local $/; chomp($log_msg{msg} = <$msg>); }
757 close $msg or croak $!;
759 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
760 print "Committing $commit: $oneline\n";
762 if (defined $LC_ALL) {
763 $ENV{LC_ALL} = $LC_ALL;
767 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
770 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
771 if (!defined $committed) {
772 my $out = join("\n",@ci_output);
773 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
774 $out, "\n\nAssuming English locale...";
775 ($committed) = ($out =~ /^Committed revision \d+\./sm);
776 defined $committed or die " FAILED!\n",
777 "Commit output failed to parse committed revision!\n",
778 print STDERR " OK\n";
781 my @svn_up = qw(svn up);
782 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
783 if ($committed == ($svn_rev + 1)) {
784 push @svn_up, "-r$committed";
786 my $info = svn_info('.');
787 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
788 if ($info->{'Last Changed Rev'} != $committed) {
789 croak "$info->{'Last Changed Rev'} != $committed\n"
791 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
792 /(\d{4})\-(\d\d)\-(\d\d)\s
793 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
794 or croak "Failed to parse date: $date\n";
795 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
796 $log_msg{author} = $info->{'Last Changed Author'};
797 $log_msg{revision} = $committed;
798 $log_msg{msg} .= "\n";
799 my $parent = file_to_s("$REV_DIR/$svn_rev");
800 git_commit(\%log_msg, $parent, $commit);
804 push @svn_up, "-r$svn_rev";
806 return fetch("$committed=$commit")->{revision};
809 # read the entire log into a temporary file (which is removed ASAP)
810 # and store the file handle + parser state
813 my $log_fh = IO::File->new_tmpfile or croak $!;
815 defined $pid or croak $!;
817 open STDOUT, '>&', $log_fh or croak $!;
818 exec (qw(svn log), @log_args) or croak $!
822 seek $log_fh, 0, 0 or croak $!;
823 return { state => 'sep', fh => $log_fh };
827 my $log = shift; # retval of svn_log_raw()
834 if ($log->{state} eq 'msg') {
836 $ret->{msg} .= $_."\n";
837 unless(--$ret->{lines}) {
838 $log->{state} = 'sep';
841 croak "Log parse error at: $_\n",
847 if ($log->{state} ne 'sep') {
848 croak "Log parse error at: $_\n",
849 "state: $log->{state}\n",
853 $log->{state} = 'rev';
855 # if we have an empty log message, put something there:
857 $ret->{msg} ||= "\n";
858 delete $ret->{lines};
863 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
865 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
866 ($lines) = ($lines =~ /(\d+)/);
867 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
868 /(\d{4})\-(\d\d)\-(\d\d)\s
869 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
870 or croak "Failed to parse date: $date\n";
871 $ret = { revision => $rev,
872 date => "$tz $Y-$m-$d $H:$M:$S",
876 if (defined $_authors && ! defined $users{$author}) {
877 die "Author: $author not defined in ",
880 $log->{state} = 'msg_start';
883 # skip the first blank line of the message:
884 if ($log->{state} eq 'msg_start' && /^$/) {
885 $log->{state} = 'msg';
886 } elsif ($log->{state} eq 'msg') {
888 $ret->{msg} .= $_."\n";
889 unless (--$ret->{lines}) {
890 $log->{state} = 'sep';
893 croak "Log parse error at: $_\n",
894 $ret->{revision},"\n";
902 my $url = shift || $SVN_URL;
904 my $pid = open my $info_fh, '-|';
905 defined $pid or croak $!;
908 exec(qw(svn info),$url) or croak $!;
912 # only single-lines seem to exist in svn info output
915 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
917 push @{$ret->{-order}}, $1;
920 close $info_fh or croak $!;
924 sub sys { system(@_) == 0 or croak $? }
927 my ($from, $to) = @_;
928 my $es = svn_propget_base('svn:eol-style', $to);
929 open my $rfd, '<', $from or croak $!;
930 binmode $rfd or croak $!;
931 open my $wfd, '>', $to or croak $!;
932 binmode $wfd or croak $!;
934 my $eol = $EOL{$es} or undef;
939 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
942 if ($buf =~ /\015$/) {
944 defined($r = sysread($rfd,$c,1)) or croak $!;
945 $buf .= $c if $r > 0;
947 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
950 for ($w = 0; $w < $r; $w += $t) {
951 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
957 sub do_update_index {
958 my ($z_cmd, $cmd, $no_text_base) = @_;
960 my $z = open my $p, '-|';
961 defined $z or croak $!;
962 unless ($z) { exec @$z_cmd or croak $! }
964 my $pid = open my $ui, '|-';
965 defined $pid or croak $!;
967 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
970 while (my $x = <$p>) {
972 if (!$no_text_base && lstat $x && ! -l _ &&
973 svn_propget_base('svn:keywords', $x)) {
974 my $mode = -x _ ? 0755 : 0644;
975 my ($v,$d,$f) = File::Spec->splitpath($x);
976 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
977 'text-base',"$f.svn-base");
980 $tb = File::Spec->catfile($d, '.svn',
981 'text-base',"$f.svn-base");
984 unlink $x or croak $!;
986 chmod(($mode &~ umask), $x) or croak $!;
990 close $ui or croak $!;
994 my $no_text_base = shift;
995 do_update_index([qw/git-diff-files --name-only -z/],
998 do_update_index([qw/git-ls-files -z --others/,
999 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1005 my ($str, $file, $mode) = @_;
1006 open my $fd,'>',$file or croak $!;
1007 print $fd $str,"\n" or croak $!;
1008 close $fd or croak $!;
1009 chmod ($mode &~ umask, $file) if (defined $mode);
1014 open my $fd,'<',$file or croak "$!: file: $file\n";
1017 close $fd or croak $!;
1022 sub assert_revision_unknown {
1024 if (-f "$REV_DIR/$revno") {
1025 croak "$REV_DIR/$revno already exists! ",
1026 "Why are we refetching it?";
1032 my @x = safe_qx('git-cat-file','commit',$x);
1033 my @y = safe_qx('git-cat-file','commit',$y);
1034 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1035 || $y[0] !~ /^tree $sha1\n$/) {
1036 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1042 sub assert_revision_eq_or_unknown {
1043 my ($revno, $commit) = @_;
1044 if (-f "$REV_DIR/$revno") {
1045 my $current = file_to_s("$REV_DIR/$revno");
1046 if (($commit ne $current) && !trees_eq($commit, $current)) {
1047 croak "$REV_DIR/$revno already exists!\n",
1048 "current: $current\nexpected: $commit\n";
1055 my ($log_msg, @parents) = @_;
1056 assert_revision_unknown($log_msg->{revision});
1057 my $out_fh = IO::File->new_tmpfile or croak $!;
1059 map_tree_joins() if (@_branch_from && !%tree_map);
1061 # commit parents can be conditionally bound to a particular
1062 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1064 foreach my $p (@parents) {
1065 next unless defined $p;
1066 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1067 if ($1 == $log_msg->{revision}) {
1068 push @exec_parents, $2;
1071 push @exec_parents, $p if $p =~ /$sha1_short/o;
1076 defined $pid or croak $!;
1078 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1080 chomp(my $tree = `git-write-tree`);
1082 if (exists $tree_map{$tree}) {
1083 my %seen_parent = map { $_ => 1 } @exec_parents;
1084 foreach (@{$tree_map{$tree}}) {
1085 # MAXPARENT is defined to 16 in commit-tree.c:
1086 if ($seen_parent{$_} || @exec_parents > 16) {
1089 push @exec_parents, $_;
1090 $seen_parent{$_} = 1;
1093 my $msg_fh = IO::File->new_tmpfile or croak $!;
1094 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1095 "$SVN_URL\@$log_msg->{revision}",
1096 " $SVN_UUID\n" or croak $!;
1097 $msg_fh->flush == 0 or croak $!;
1098 seek $msg_fh, 0, 0 or croak $!;
1100 set_commit_env($log_msg);
1102 my @exec = ('git-commit-tree',$tree);
1103 push @exec, '-p', $_ foreach @exec_parents;
1104 open STDIN, '<&', $msg_fh or croak $!;
1105 open STDOUT, '>&', $out_fh or croak $!;
1106 exec @exec or croak $!;
1111 $out_fh->flush == 0 or croak $!;
1112 seek $out_fh, 0, 0 or croak $!;
1113 chomp(my $commit = do { local $/; <$out_fh> });
1114 if ($commit !~ /^$sha1$/o) {
1115 croak "Failed to commit, invalid sha1: $commit\n";
1117 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1118 if (my $primary_parent = shift @exec_parents) {
1120 defined $pid or croak $!;
1124 exec 'git-rev-parse','--verify',
1125 "refs/remotes/$GIT_SVN^0" or croak $!;
1128 push @update_ref, $primary_parent unless $?;
1131 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
1132 print "r$log_msg->{revision} = $commit\n";
1133 if ($_repack && (--$_repack_nr == 0)) {
1134 $_repack_nr = $_repack;
1135 sys("git repack $_repack_flags");
1140 sub set_commit_env {
1142 my $author = $log_msg->{author};
1143 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1144 : ($author,"$author\@$SVN_UUID");
1145 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1146 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1147 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1150 sub apply_mod_line_blob {
1152 if ($m->{mode_b} =~ /^120/) {
1153 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1155 blob_to_file($m->{sha1_b}, $m->{file_b});
1159 sub blob_to_symlink {
1160 my ($blob, $link) = @_;
1161 defined $link or croak "\$link not defined!\n";
1162 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1163 if (-l $link || -f _) {
1164 unlink $link or croak $!;
1167 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1168 symlink $dest, $link or croak $!;
1172 my ($blob, $file) = @_;
1173 defined $file or croak "\$file not defined!\n";
1174 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1175 if (-l $file || -f _) {
1176 unlink $file or croak $!;
1179 open my $blob_fh, '>', $file or croak "$!: $file\n";
1181 defined $pid or croak $!;
1184 open STDOUT, '>&', $blob_fh or croak $!;
1185 exec('git-cat-file','blob',$blob) or croak $!;
1190 close $blob_fh or croak $!;
1194 my $pid = open my $child, '-|';
1195 defined $pid or croak $!;
1197 exec(@_) or croak $!;
1199 my @ret = (<$child>);
1200 close $child or croak $?;
1201 die $? if $?; # just in case close didn't error out
1202 return wantarray ? @ret : join('',@ret);
1205 sub svn_compat_check {
1206 my @co_help = safe_qx(qw(svn co -h));
1207 unless (grep /ignore-externals/,@co_help) {
1208 print STDERR "W: Installed svn version does not support ",
1209 "--ignore-externals\n";
1210 $_no_ignore_ext = 1;
1212 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1213 $_svn_co_url_revs = 1;
1215 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1216 $_svn_pg_peg_revs = 1;
1219 # I really, really hope nobody hits this...
1220 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1222 W: The installed svn version does not support the --stop-on-copy flag in
1224 Lets hope the directory you're tracking is not a branch or tag
1225 and was never moved within the repository...
1231 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1232 # (and they won't honor URL@<rev> without -r<rev>, too!)
1233 sub svn_cmd_checkout {
1234 my ($url, $rev, $dir) = @_;
1235 my @cmd = ('svn','co', "-r$rev");
1236 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1237 $url .= "\@$rev" if $_svn_co_url_revs;
1238 sys(@cmd, $url, $dir);
1241 sub check_upgrade_needed {
1243 my $pid = open my $child, '-|';
1244 defined $pid or croak $!;
1247 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1249 my @ret = (<$child>);
1250 close $child or croak $?;
1251 die $? if $?; # just in case close didn't error out
1252 return wantarray ? @ret : join('',@ret);
1255 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1257 print STDERR "Please run: $0 rebuild --upgrade\n";
1262 # fills %tree_map with a reverse mapping of trees to commits. Useful
1263 # for finding parents to commit on.
1264 sub map_tree_joins {
1266 foreach my $br (@_branch_from) {
1267 my $pid = open my $pipe, '-|';
1268 defined $pid or croak $!;
1270 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1274 if (/^commit ($sha1)$/o) {
1277 # if we've seen a commit,
1278 # we've seen its parents
1279 last if $seen{$commit};
1280 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1281 unless (defined $tree) {
1282 die "Failed to parse commit $commit\n";
1284 push @{$tree_map{$tree}}, $commit;
1288 close $pipe; # we could be breaking the pipe early
1293 if (@_branch_from) {
1294 print STDERR '--branch|-b parameters are ignored when ',
1295 "--branch-all-refs|-B is passed\n";
1298 # don't worry about rev-list on non-commit objects/tags,
1299 # it shouldn't blow up if a ref is a blob or tree...
1300 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1303 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1305 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1306 while (<$authors>) {
1308 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1309 my ($user, $name, $email) = ($1, $2, $3);
1310 $users{$user} = [$name, $email];
1312 close $authors or croak $!;
1315 sub svn_propget_base {
1317 $f .= '@BASE' if $_svn_pg_peg_revs;
1318 return safe_qx(qw/svn propget/, $p, $f);
1321 sub migration_check {
1322 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1323 print "Upgrading repository...\n";
1324 unless (-d "$GIT_DIR/svn") {
1325 mkdir "$GIT_DIR/svn" or croak $!;
1327 print "Data from a previous version of git-svn exists, but\n\t",
1328 "$GIT_SVN_DIR\n\t(required for this version ",
1329 "($VERSION) of git-svn) does not.\n";
1331 foreach my $x (`git-rev-parse --symbolic --all`) {
1332 next unless $x =~ s#^refs/remotes/##;
1334 next unless -f "$GIT_DIR/$x/info/url";
1335 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1337 my $dn = dirname("$GIT_DIR/svn/$x");
1338 mkpath([$dn]) unless -d $dn;
1339 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1340 my ($url, $path) = repo_path_split($u);
1341 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
1342 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
1344 print "Done upgrading.\n";
1348 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1349 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1350 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1352 $REV_DIR = "$GIT_SVN_DIR/revs";
1353 $SVN_WC = "$GIT_SVN_DIR/tree";
1356 # convert GetOpt::Long specs for use by git-repo-config
1357 sub read_repo_config {
1358 return unless -d $GIT_DIR;
1360 foreach my $o (keys %$opts) {
1361 my $v = $opts->{$o};
1362 my ($key) = ($o =~ /^([a-z\-]+)/);
1364 my $arg = 'git-repo-config';
1365 $arg .= ' --int' if ($o =~ /[:=]i$/);
1366 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1367 if (ref $v eq 'ARRAY') {
1368 chomp(my @tmp = `$arg --get-all svn.$key`);
1371 chomp(my $tmp = `$arg --get svn.$key`);
1372 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
1379 sub set_default_vals {
1380 if (defined $_repack) {
1381 $_repack = 1000 if ($_repack <= 0);
1382 $_repack_nr = $_repack;
1383 $_repack_flags ||= '';
1391 $svn_log hashref (as returned by svn_log_raw)
1393 fh => file handle of the log file,
1394 state => state of the log file parser (sep/msg/rev/msg_start...)
1397 $log_msg hashref as returned by next_log_entry($svn_log)
1399 msg => 'whitespace-formatted log entry
1400 ', # trailing newline is preserved
1401 revision => '8', # integer
1402 date => '2004-02-24T17:01:44.108345Z', # commit date
1403 author => 'committer name'
1407 @mods = array of diff-index line hashes, each element represents one line
1408 of diff-index output
1410 diff-index line ($m hash)
1412 mode_a => first column of diff-index output, no leading ':',
1413 mode_b => second column of diff-index output,
1414 sha1_b => sha1sum of the final blob,
1415 chg => change type [MCRADT],
1416 file_a => original file name of a file (iff chg is 'C' or 'R')
1417 file_b => new/current file name of a file (any chg)