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
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);
41 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
42 'branch|b=s' => \@_branch_from,
43 'branch-all-refs|B' => \$_branch_all_refs,
44 'authors-file|A=s' => \$_authors );
46 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
47 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
50 fetch => [ \&fetch, "Download new revisions from SVN",
51 { 'revision|r=s' => \$_revision, %fc_opts } ],
52 init => [ \&init, "Initialize a repo for tracking" .
53 " (requires URL argument)", { } ],
54 commit => [ \&commit, "Commit git revisions to SVN",
55 { 'stdin|' => \$_stdin,
58 'find-copies-harder' => \$_find_copies_harder,
60 'copy-similarity|C=i'=> \$_cp_similarity,
63 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
64 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
65 { 'no-ignore-externals' => \$_no_ignore_ext,
66 'upgrade' => \$_upgrade } ],
69 for (my $i = 0; $i < @ARGV; $i++) {
70 if (defined $cmd{$ARGV[$i]}) {
77 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
79 # convert GetOpt::Long specs for use by git-repo-config
80 foreach my $o (keys %opts) {
82 my ($key) = ($o =~ /^([a-z\-]+)/);
84 my $arg = 'git-repo-config';
85 $arg .= ' --int' if ($o =~ /=i$/);
86 $arg .= ' --bool' if ($o !~ /=[sfi]$/);
87 if (ref $v eq 'ARRAY') {
88 chomp(my @tmp = `$arg --get-all svn.$key`);
91 chomp(my $tmp = `$arg --get svn.$key`);
92 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
98 GetOptions(%opts, 'help|H|h' => \$_help,
99 'version|V' => \$_version,
100 'id|i=s' => \$GIT_SVN) or exit 1;
102 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
103 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
105 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
106 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
109 version() if $_version;
110 usage(1) unless defined $cmd;
111 load_authors() if $_authors;
112 load_all_refs() if $_branch_all_refs;
114 $cmd{$cmd}->[0]->(@ARGV);
117 ####################### primary functions ######################
119 my $exit = shift || 0;
120 my $fd = $exit ? \*STDERR : \*STDOUT;
122 git-svn - bidirectional operations between a single Subversion tree and git
123 Usage: $0 <command> [options] [arguments]\n
125 print $fd "Available commands:\n" unless $cmd;
127 foreach (sort keys %cmd) {
128 next if $cmd && $cmd ne $_;
129 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
130 foreach (keys %{$cmd{$_}->[2]}) {
131 # prints out arguments as they should be passed:
132 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
133 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
135 split /\|/,$_)," $x\n";
139 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
140 arbitrary identifier if you're tracking multiple SVN branches/repositories in
141 one git repository and want to keep them separate. See git-svn(1) for more
148 print "git-svn version $VERSION\n";
153 $SVN_URL = shift or undef;
156 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
158 check_upgrade_needed();
161 my $pid = open(my $rev_list,'-|');
162 defined $pid or croak $!;
164 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
167 while (<$rev_list>) {
170 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
171 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
172 next if (!@commit); # skip merges
173 my $id = $commit[$#commit];
174 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
176 if (!$rev || !$uuid || !$url) {
177 # some of the original repositories I made had
178 # indentifiers like this:
179 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
181 if (!$rev || !$uuid) {
182 croak "Unable to extract revision or UUID from ",
187 # if we merged or otherwise started elsewhere, this is
188 # how we break out of it
189 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
190 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
192 print "r$rev = $c\n";
193 unless (defined $latest) {
194 if (!$SVN_URL && !$url) {
195 croak "SVN repository location required: $url\n";
202 assert_revision_eq_or_unknown($rev, $c);
203 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
204 $newest_rev = $rev if ($rev > $newest_rev);
206 close $rev_list or croak $?;
207 if (!chdir $SVN_WC) {
208 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
209 chdir $SVN_WC or croak $!;
213 defined $pid or croak $!;
215 my @svn_up = qw(svn up);
216 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
217 sys(@svn_up,"-r$newest_rev");
218 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
220 exec('git-write-tree');
226 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
227 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
233 $SVN_URL = shift or die "SVN repository location required " .
234 "as a command-line argument\n";
235 unless (-d $GIT_DIR) {
243 check_upgrade_needed();
244 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
245 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
246 unless ($_revision) {
247 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
249 push @log_args, "-r$_revision";
250 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
252 my $svn_log = svn_log_raw(@log_args);
254 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
255 my $last_commit = undef;
256 unless (-d $SVN_WC) {
257 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
258 chdir $SVN_WC or croak $!;
260 $last_commit = git_commit($base, @parents);
261 assert_tree($last_commit);
263 chdir $SVN_WC or croak $!;
265 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
266 # looks like a user manually cp'd and svn switch'ed
267 unless ($last_commit) {
268 sys(qw/svn revert -R ./);
269 assert_svn_wc_clean($base->{revision});
270 $last_commit = git_commit($base, @parents);
271 assert_tree($last_commit);
274 my @svn_up = qw(svn up);
275 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
277 while (my $log_msg = next_log_entry($svn_log)) {
278 assert_tree($last_commit);
279 if ($last->{revision} >= $log_msg->{revision}) {
280 croak "Out of order: last >= current: ",
281 "$last->{revision} >= $log_msg->{revision}\n";
283 # Revert is needed for cases like:
284 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
285 # I can't seem to reproduce something like that on a test...
286 sys(qw/svn revert -R ./);
287 assert_svn_wc_clean($last->{revision});
288 sys(@svn_up,"-r$log_msg->{revision}");
289 $last_commit = git_commit($log_msg, $last_commit, @parents);
292 unless (-e "$GIT_DIR/refs/heads/master") {
293 sys(qw(git-update-ref refs/heads/master),$last_commit);
300 check_upgrade_needed();
301 if ($_stdin || !@commits) {
302 print "Reading from stdin...\n";
305 if (/\b($sha1_short)\b/o) {
306 unshift @commits, $1;
311 foreach my $c (@commits) {
312 chomp(my @tmp = safe_qx('git-rev-parse',$c));
313 if (scalar @tmp == 1) {
315 } elsif (scalar @tmp > 1) {
316 push @revs, reverse (safe_qx('git-rev-list',@tmp));
318 die "Failed to rev-parse $c\n";
323 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
324 my $info = svn_info('.');
325 my $fetched = fetch();
326 if ($info->{Revision} != $fetched->{revision}) {
327 print STDERR "There are new revisions that were fetched ",
328 "and need to be merged (or acknowledged) ",
329 "before committing.\n";
332 $info = svn_info('.');
334 my $svn_current_rev = $info->{'Last Changed Rev'};
335 foreach my $c (@revs) {
336 my $mods = svn_checkout_tree($svn_current_rev, $c);
337 if (scalar @$mods == 0) {
338 print "Skipping, no changes detected\n";
341 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
343 print "Done committing ",scalar @revs," revisions to SVN\n";
347 require File::Find or die $!;
348 my $exclude_file = "$GIT_DIR/info/exclude";
349 open my $fh, '<', $exclude_file or croak $!;
350 chomp(my @excludes = (<$fh>));
351 close $fh or croak $!;
353 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
354 chdir $SVN_WC or croak $!;
356 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
358 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
359 }}, no_chdir=>1},'.');
362 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
364 foreach my $i (sort keys %ign) {
365 print "\n# ",$i,"\n";
366 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
370 ########################### utility functions #########################
374 my $info = shift || svn_info('.');
375 $SVN_UUID = $info->{'Repository UUID'} or
376 croak "Repository UUID unreadable\n";
377 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
381 defined $SVN_URL or croak "SVN repository location required\n";
382 unless (-d $GIT_DIR) {
383 croak "GIT_DIR=$GIT_DIR does not exist!\n";
385 mkpath(["$GIT_DIR/$GIT_SVN"]);
386 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
388 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
390 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
391 print $fd '.svn',"\n";
392 close $fd or croak $!;
395 sub assert_svn_wc_clean {
397 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
398 my $lcr = svn_info('.')->{'Last Changed Rev'};
399 if ($svn_rev != $lcr) {
400 print STDERR "Checking for copy-tree ... ";
401 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
402 "-r$lcr:$svn_rev")));
404 croak "Nope! Expected r$svn_rev, got r$lcr\n";
406 print STDERR "OK!\n";
409 my @status = grep(!/^Performing status on external/,(`svn status`));
410 @status = grep(!/^\s*$/,@status);
411 if (scalar @status) {
412 print STDERR "Tree ($SVN_WC) is not clean:\n";
413 print STDERR $_ foreach @status;
420 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
421 chomp(my $type = `git-cat-file -t $treeish`);
423 while ($type eq 'tag') {
424 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
426 if ($type eq 'commit') {
427 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
428 ($expected) = ($expected =~ /^tree ($sha1)$/);
429 die "Unable to get tree from $treeish\n" unless $expected;
430 } elsif ($type eq 'tree') {
431 $expected = $treeish;
433 die "$treeish is a $type, expected tree, tag or commit\n";
436 my $old_index = $ENV{GIT_INDEX_FILE};
437 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
439 unlink $tmpindex or croak $!;
441 $ENV{GIT_INDEX_FILE} = $tmpindex;
443 chomp(my $tree = `git-write-tree`);
445 $ENV{GIT_INDEX_FILE} = $old_index;
447 delete $ENV{GIT_INDEX_FILE};
449 if ($tree ne $expected) {
450 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
455 sub parse_diff_tree {
461 chomp $_; # this gets rid of the trailing "\0"
462 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
463 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
464 push @mods, { mode_a => $1, mode_b => $2,
465 sha1_b => $3, chg => $4 };
466 if ($4 =~ /^(?:C|R)$/) {
471 } elsif ($state eq 'file_a') {
472 my $x = $mods[$#mods] or croak "Empty array\n";
473 if ($x->{chg} !~ /^(?:C|R)$/) {
474 croak "Error parsing $_, $x->{chg}\n";
478 } elsif ($state eq 'file_b') {
479 my $x = $mods[$#mods] or croak "Empty array\n";
480 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
481 croak "Error parsing $_, $x->{chg}\n";
483 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
484 croak "Error parsing $_, $x->{chg}\n";
489 croak "Error parsing $_\n";
492 close $diff_fh or croak $!;
497 sub svn_check_prop_executable {
499 return if -l $m->{file_b};
500 if ($m->{mode_b} =~ /755$/) {
501 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
502 if ($m->{mode_a} !~ /755$/) {
503 sys(qw(svn propset svn:executable 1), $m->{file_b});
505 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
506 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
507 sys(qw(svn propdel svn:executable), $m->{file_b});
508 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
509 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
513 sub svn_ensure_parent_path {
514 my $dir_b = dirname(shift);
515 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
516 mkpath([$dir_b]) unless (-d $dir_b);
517 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
520 sub precommit_check {
522 my (%rm_file, %rmdir_check, %added_check);
524 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
525 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
526 if ($m->{chg} eq 'R') {
527 if (-d $m->{file_b}) {
528 err_dir_to_file("$m->{file_a} => $m->{file_b}");
530 # dir/$file => dir/file/$file
531 my $dirname = dirname($m->{file_b});
532 while ($dirname ne File::Spec->curdir) {
533 if ($dirname ne $m->{file_a}) {
534 $dirname = dirname($dirname);
537 err_file_to_dir("$m->{file_a} => $m->{file_b}");
539 # baz/zzz => baz (baz is a file)
540 $dirname = dirname($m->{file_a});
541 while ($dirname ne File::Spec->curdir) {
542 if ($dirname ne $m->{file_b}) {
543 $dirname = dirname($dirname);
546 err_dir_to_file("$m->{file_a} => $m->{file_b}");
549 if ($m->{chg} =~ /^(D|R)$/) {
550 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
551 $rm_file{ $m->{$t} } = 1;
552 my $dirname = dirname( $m->{$t} );
553 my $basename = basename( $m->{$t} );
554 $rmdir_check{$dirname}->{$basename} = 1;
555 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
556 if (-d $m->{file_b}) {
557 err_dir_to_file($m->{file_b});
559 my $dirname = dirname( $m->{file_b} );
560 my $basename = basename( $m->{file_b} );
561 $added_check{$dirname}->{$basename} = 1;
562 while ($dirname ne File::Spec->curdir) {
563 if ($rm_file{$dirname}) {
564 err_file_to_dir($m->{file_b});
566 $dirname = dirname $dirname;
570 return (\%rmdir_check, \%added_check);
572 sub err_dir_to_file {
574 print STDERR "Node change from directory to file ",
575 "is not supported by Subversion: ",$file,"\n";
578 sub err_file_to_dir {
580 print STDERR "Node change from file to directory ",
581 "is not supported by Subversion: ",$file,"\n";
586 sub svn_checkout_tree {
587 my ($svn_rev, $treeish) = @_;
588 my $from = file_to_s("$REV_DIR/$svn_rev");
590 print "diff-tree $from $treeish\n";
591 my $pid = open my $diff_fh, '-|';
592 defined $pid or croak $!;
594 my @diff_tree = qw(git-diff-tree -z -r);
595 if ($_cp_similarity) {
596 push @diff_tree, "-C$_cp_similarity";
598 push @diff_tree, '-C';
600 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
601 push @diff_tree, "-l$_l" if defined $_l;
602 exec(@diff_tree, $from, $treeish) or croak $!;
604 my $mods = parse_diff_tree($diff_fh);
606 # git can do empty commits, but SVN doesn't allow it...
609 my ($rm, $add) = precommit_check($mods);
611 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
612 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
613 if ($m->{chg} eq 'C') {
614 svn_ensure_parent_path( $m->{file_b} );
615 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
616 apply_mod_line_blob($m);
617 svn_check_prop_executable($m);
618 } elsif ($m->{chg} eq 'D') {
619 sys(qw(svn rm --force), $m->{file_b});
620 } elsif ($m->{chg} eq 'R') {
621 svn_ensure_parent_path( $m->{file_b} );
622 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
623 apply_mod_line_blob($m);
624 svn_check_prop_executable($m);
625 } elsif ($m->{chg} eq 'M') {
626 apply_mod_line_blob($m);
627 svn_check_prop_executable($m);
628 } elsif ($m->{chg} eq 'T') {
629 sys(qw(svn rm --force),$m->{file_b});
630 apply_mod_line_blob($m);
631 sys(qw(svn add --force), $m->{file_b});
632 svn_check_prop_executable($m);
633 } elsif ($m->{chg} eq 'A') {
634 svn_ensure_parent_path( $m->{file_b} );
635 apply_mod_line_blob($m);
636 sys(qw(svn add --force), $m->{file_b});
637 svn_check_prop_executable($m);
639 croak "Invalid chg: $m->{chg}\n";
643 assert_tree($treeish);
644 if ($_rmdir) { # remove empty directories
645 handle_rmdir($rm, $add);
647 assert_tree($treeish);
651 # svn ls doesn't work with respect to the current working tree, but what's
652 # in the repository. There's not even an option for it... *sigh*
653 # (added files don't show up and removed files remain in the ls listing)
655 my ($dir, $rm, $add) = @_;
656 chomp(my @ls = safe_qx('svn','ls',$dir));
659 s#/$##; # trailing slashes are evil
660 push @ret, $_ unless $rm->{$dir}->{$_};
662 if (exists $add->{$dir}) {
663 push @ret, keys %{$add->{$dir}};
671 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
672 my $ls = svn_ls_current($dir, $rm, $add);
673 next if (scalar @$ls);
674 sys(qw(svn rm --force),$dir);
676 my $dn = dirname $dir;
677 $rm->{ $dn }->{ basename $dir } = 1;
678 $ls = svn_ls_current($dn, $rm, $add);
679 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
680 sys(qw(svn rm --force),$dn);
683 $rm->{ $dn }->{ $dir } = 1;
684 $ls = svn_ls_current($dn, $rm, $add);
689 sub svn_commit_tree {
690 my ($svn_rev, $commit) = @_;
691 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
692 my %log_msg = ( msg => '' );
693 open my $msg, '>', $commit_msg or croak $!;
695 chomp(my $type = `git-cat-file -t $commit`);
696 if ($type eq 'commit') {
697 my $pid = open my $msg_fh, '-|';
698 defined $pid or croak $!;
701 exec(qw(git-cat-file commit), $commit) or croak $!;
706 $in_msg = 1 if (/^\s*$/);
707 } elsif (/^git-svn-id: /) {
708 # skip this, we regenerate the correct one
709 # on re-fetch anyways
711 print $msg $_ or croak $!;
714 close $msg_fh or croak $!;
716 close $msg or croak $!;
718 if ($_edit || ($type eq 'tree')) {
719 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
720 system($editor, $commit_msg);
723 # file_to_s removes all trailing newlines, so just use chomp() here:
724 open $msg, '<', $commit_msg or croak $!;
725 { local $/; chomp($log_msg{msg} = <$msg>); }
726 close $msg or croak $!;
728 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
729 print "Committing $commit: $oneline\n";
731 if (defined $LC_ALL) {
732 $ENV{LC_ALL} = $LC_ALL;
736 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
739 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
740 if (!defined $committed) {
741 my $out = join("\n",@ci_output);
742 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
743 $out, "\n\nAssuming English locale...";
744 ($committed) = ($out =~ /^Committed revision \d+\./sm);
745 defined $committed or die " FAILED!\n",
746 "Commit output failed to parse committed revision!\n",
747 print STDERR " OK\n";
750 my @svn_up = qw(svn up);
751 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
752 if ($committed == ($svn_rev + 1)) {
753 push @svn_up, "-r$committed";
755 my $info = svn_info('.');
756 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
757 if ($info->{'Last Changed Rev'} != $committed) {
758 croak "$info->{'Last Changed Rev'} != $committed\n"
760 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
761 /(\d{4})\-(\d\d)\-(\d\d)\s
762 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
763 or croak "Failed to parse date: $date\n";
764 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
765 $log_msg{author} = $info->{'Last Changed Author'};
766 $log_msg{revision} = $committed;
767 $log_msg{msg} .= "\n";
768 my $parent = file_to_s("$REV_DIR/$svn_rev");
769 git_commit(\%log_msg, $parent, $commit);
773 push @svn_up, "-r$svn_rev";
775 return fetch("$committed=$commit")->{revision};
778 # read the entire log into a temporary file (which is removed ASAP)
779 # and store the file handle + parser state
782 my $log_fh = IO::File->new_tmpfile or croak $!;
784 defined $pid or croak $!;
786 open STDOUT, '>&', $log_fh or croak $!;
787 exec (qw(svn log), @log_args) or croak $!
791 seek $log_fh, 0, 0 or croak $!;
792 return { state => 'sep', fh => $log_fh };
796 my $log = shift; # retval of svn_log_raw()
803 if ($log->{state} eq 'msg') {
805 $ret->{msg} .= $_."\n";
806 unless(--$ret->{lines}) {
807 $log->{state} = 'sep';
810 croak "Log parse error at: $_\n",
816 if ($log->{state} ne 'sep') {
817 croak "Log parse error at: $_\n",
818 "state: $log->{state}\n",
822 $log->{state} = 'rev';
824 # if we have an empty log message, put something there:
826 $ret->{msg} ||= "\n";
827 delete $ret->{lines};
832 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
834 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
835 ($lines) = ($lines =~ /(\d+)/);
836 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
837 /(\d{4})\-(\d\d)\-(\d\d)\s
838 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
839 or croak "Failed to parse date: $date\n";
840 $ret = { revision => $rev,
841 date => "$tz $Y-$m-$d $H:$M:$S",
845 if (defined $_authors && ! defined $users{$author}) {
846 die "Author: $author not defined in ",
849 $log->{state} = 'msg_start';
852 # skip the first blank line of the message:
853 if ($log->{state} eq 'msg_start' && /^$/) {
854 $log->{state} = 'msg';
855 } elsif ($log->{state} eq 'msg') {
857 $ret->{msg} .= $_."\n";
858 unless (--$ret->{lines}) {
859 $log->{state} = 'sep';
862 croak "Log parse error at: $_\n",
863 $ret->{revision},"\n";
871 my $url = shift || $SVN_URL;
873 my $pid = open my $info_fh, '-|';
874 defined $pid or croak $!;
877 exec(qw(svn info),$url) or croak $!;
881 # only single-lines seem to exist in svn info output
884 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
886 push @{$ret->{-order}}, $1;
889 close $info_fh or croak $!;
893 sub sys { system(@_) == 0 or croak $? }
896 my ($from, $to) = @_;
897 my $es = svn_propget_base('svn:eol-style', $to);
898 open my $rfd, '<', $from or croak $!;
899 binmode $rfd or croak $!;
900 open my $wfd, '>', $to or croak $!;
901 binmode $wfd or croak $!;
903 my $eol = $EOL{$es} or undef;
908 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
911 if ($buf =~ /\015$/) {
913 defined($r = sysread($rfd,$c,1)) or croak $!;
914 $buf .= $c if $r > 0;
916 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
919 for ($w = 0; $w < $r; $w += $t) {
920 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
926 sub do_update_index {
927 my ($z_cmd, $cmd, $no_text_base) = @_;
929 my $z = open my $p, '-|';
930 defined $z or croak $!;
931 unless ($z) { exec @$z_cmd or croak $! }
933 my $pid = open my $ui, '|-';
934 defined $pid or croak $!;
936 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
939 while (my $x = <$p>) {
941 if (!$no_text_base && lstat $x && ! -l _ &&
942 svn_propget_base('svn:keywords', $x)) {
943 my $mode = -x _ ? 0755 : 0644;
944 my ($v,$d,$f) = File::Spec->splitpath($x);
945 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
946 'text-base',"$f.svn-base");
949 $tb = File::Spec->catfile($d, '.svn',
950 'text-base',"$f.svn-base");
953 unlink $x or croak $!;
955 chmod(($mode &~ umask), $x) or croak $!;
959 close $ui or croak $!;
963 my $no_text_base = shift;
964 do_update_index([qw/git-diff-files --name-only -z/],
967 do_update_index([qw/git-ls-files -z --others/,
968 "--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude"],
974 my ($str, $file, $mode) = @_;
975 open my $fd,'>',$file or croak $!;
976 print $fd $str,"\n" or croak $!;
977 close $fd or croak $!;
978 chmod ($mode &~ umask, $file) if (defined $mode);
983 open my $fd,'<',$file or croak "$!: file: $file\n";
986 close $fd or croak $!;
991 sub assert_revision_unknown {
993 if (-f "$REV_DIR/$revno") {
994 croak "$REV_DIR/$revno already exists! ",
995 "Why are we refetching it?";
1001 my @x = safe_qx('git-cat-file','commit',$x);
1002 my @y = safe_qx('git-cat-file','commit',$y);
1003 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1004 || $y[0] !~ /^tree $sha1\n$/) {
1005 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1011 sub assert_revision_eq_or_unknown {
1012 my ($revno, $commit) = @_;
1013 if (-f "$REV_DIR/$revno") {
1014 my $current = file_to_s("$REV_DIR/$revno");
1015 if (($commit ne $current) && !trees_eq($commit, $current)) {
1016 croak "$REV_DIR/$revno already exists!\n",
1017 "current: $current\nexpected: $commit\n";
1024 my ($log_msg, @parents) = @_;
1025 assert_revision_unknown($log_msg->{revision});
1026 my $out_fh = IO::File->new_tmpfile or croak $!;
1028 map_tree_joins() if (@_branch_from && !%tree_map);
1030 # commit parents can be conditionally bound to a particular
1031 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1033 foreach my $p (@parents) {
1034 next unless defined $p;
1035 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1036 if ($1 == $log_msg->{revision}) {
1037 push @exec_parents, $2;
1040 push @exec_parents, $p if $p =~ /$sha1_short/o;
1045 defined $pid or croak $!;
1047 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1049 chomp(my $tree = `git-write-tree`);
1051 if (exists $tree_map{$tree}) {
1052 my %seen_parent = map { $_ => 1 } @exec_parents;
1053 foreach (@{$tree_map{$tree}}) {
1054 # MAXPARENT is defined to 16 in commit-tree.c:
1055 if ($seen_parent{$_} || @exec_parents > 16) {
1058 push @exec_parents, $_;
1059 $seen_parent{$_} = 1;
1062 my $msg_fh = IO::File->new_tmpfile or croak $!;
1063 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1064 "$SVN_URL\@$log_msg->{revision}",
1065 " $SVN_UUID\n" or croak $!;
1066 $msg_fh->flush == 0 or croak $!;
1067 seek $msg_fh, 0, 0 or croak $!;
1069 set_commit_env($log_msg);
1071 my @exec = ('git-commit-tree',$tree);
1072 push @exec, '-p', $_ foreach @exec_parents;
1073 open STDIN, '<&', $msg_fh or croak $!;
1074 open STDOUT, '>&', $out_fh or croak $!;
1075 exec @exec or croak $!;
1080 $out_fh->flush == 0 or croak $!;
1081 seek $out_fh, 0, 0 or croak $!;
1082 chomp(my $commit = do { local $/; <$out_fh> });
1083 if ($commit !~ /^$sha1$/o) {
1084 croak "Failed to commit, invalid sha1: $commit\n";
1086 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1087 if (my $primary_parent = shift @exec_parents) {
1089 defined $pid or croak $!;
1093 exec 'git-rev-parse','--verify',
1094 "refs/remotes/$GIT_SVN^0";
1097 push @update_ref, $primary_parent unless $?;
1100 sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
1101 print "r$log_msg->{revision} = $commit\n";
1105 sub set_commit_env {
1107 my $author = $log_msg->{author};
1108 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1109 : ($author,"$author\@$SVN_UUID");
1110 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1111 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1112 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1115 sub apply_mod_line_blob {
1117 if ($m->{mode_b} =~ /^120/) {
1118 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1120 blob_to_file($m->{sha1_b}, $m->{file_b});
1124 sub blob_to_symlink {
1125 my ($blob, $link) = @_;
1126 defined $link or croak "\$link not defined!\n";
1127 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1128 if (-l $link || -f _) {
1129 unlink $link or croak $!;
1132 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1133 symlink $dest, $link or croak $!;
1137 my ($blob, $file) = @_;
1138 defined $file or croak "\$file not defined!\n";
1139 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1140 if (-l $file || -f _) {
1141 unlink $file or croak $!;
1144 open my $blob_fh, '>', $file or croak "$!: $file\n";
1146 defined $pid or croak $!;
1149 open STDOUT, '>&', $blob_fh or croak $!;
1150 exec('git-cat-file','blob',$blob);
1155 close $blob_fh or croak $!;
1159 my $pid = open my $child, '-|';
1160 defined $pid or croak $!;
1162 exec(@_) or croak $?;
1164 my @ret = (<$child>);
1165 close $child or croak $?;
1166 die $? if $?; # just in case close didn't error out
1167 return wantarray ? @ret : join('',@ret);
1170 sub svn_compat_check {
1171 my @co_help = safe_qx(qw(svn co -h));
1172 unless (grep /ignore-externals/,@co_help) {
1173 print STDERR "W: Installed svn version does not support ",
1174 "--ignore-externals\n";
1175 $_no_ignore_ext = 1;
1177 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1178 $_svn_co_url_revs = 1;
1180 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1181 $_svn_pg_peg_revs = 1;
1184 # I really, really hope nobody hits this...
1185 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1187 W: The installed svn version does not support the --stop-on-copy flag in
1189 Lets hope the directory you're tracking is not a branch or tag
1190 and was never moved within the repository...
1196 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1197 # (and they won't honor URL@<rev> without -r<rev>, too!)
1198 sub svn_cmd_checkout {
1199 my ($url, $rev, $dir) = @_;
1200 my @cmd = ('svn','co', "-r$rev");
1201 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1202 $url .= "\@$rev" if $_svn_co_url_revs;
1203 sys(@cmd, $url, $dir);
1206 sub check_upgrade_needed {
1208 my $pid = open my $child, '-|';
1209 defined $pid or croak $!;
1212 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1214 my @ret = (<$child>);
1215 close $child or croak $?;
1216 die $? if $?; # just in case close didn't error out
1217 return wantarray ? @ret : join('',@ret);
1220 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1222 print STDERR "Please run: $0 rebuild --upgrade\n";
1227 # fills %tree_map with a reverse mapping of trees to commits. Useful
1228 # for finding parents to commit on.
1229 sub map_tree_joins {
1231 foreach my $br (@_branch_from) {
1232 my $pid = open my $pipe, '-|';
1233 defined $pid or croak $!;
1235 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1239 if (/^commit ($sha1)$/o) {
1242 # if we've seen a commit,
1243 # we've seen its parents
1244 last if $seen{$commit};
1245 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1246 unless (defined $tree) {
1247 die "Failed to parse commit $commit\n";
1249 push @{$tree_map{$tree}}, $commit;
1253 close $pipe; # we could be breaking the pipe early
1258 if (@_branch_from) {
1259 print STDERR '--branch|-b parameters are ignored when ',
1260 "--branch-all-refs|-B is passed\n";
1263 # don't worry about rev-list on non-commit objects/tags,
1264 # it shouldn't blow up if a ref is a blob or tree...
1265 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1268 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1270 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1271 while (<$authors>) {
1273 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1274 my ($user, $name, $email) = ($1, $2, $3);
1275 $users{$user} = [$name, $email];
1277 close $authors or croak $!;
1280 sub svn_propget_base {
1282 $f .= '@BASE' if $_svn_pg_peg_revs;
1283 return safe_qx(qw/svn propget/, $p, $f);
1290 $svn_log hashref (as returned by svn_log_raw)
1292 fh => file handle of the log file,
1293 state => state of the log file parser (sep/msg/rev/msg_start...)
1296 $log_msg hashref as returned by next_log_entry($svn_log)
1298 msg => 'whitespace-formatted log entry
1299 ', # trailing newline is preserved
1300 revision => '8', # integer
1301 date => '2004-02-24T17:01:44.108345Z', # commit date
1302 author => 'committer name'
1306 @mods = array of diff-index line hashes, each element represents one line
1307 of diff-index output
1309 diff-index line ($m hash)
1311 mode_a => first column of diff-index output, no leading ':',
1312 mode_b => second column of diff-index output,
1313 sha1_b => sha1sum of the final blob,
1314 chg => change type [MCRADT],
1315 file_a => original file name of a file (iff chg is 'C' or 'R')
1316 file_b => new/current file name of a file (any chg)