contrib/git-svn: fix a copied-tree bug in an overzealous assertion
[git/jnareb-git.git] / contrib / git-svn / git-svn.perl
blob3c860e458c2894c0addf008e4f011abb68e8b562
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
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/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '0.10.0';
12 $GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
13 # make sure the svn binary gives consistent output between locales and TZs:
14 $ENV{TZ} = 'UTC';
15 $ENV{LC_ALL} = 'C';
17 # If SVN:: library support is added, please make the dependencies
18 # optional and preserve the capability to use the command-line client.
19 # use eval { require SVN::... } to make it lazy load
20 # We don't use any modules not in the standard Perl distribution:
21 use Carp qw/croak/;
22 use IO::File qw//;
23 use File::Basename qw/dirname basename/;
24 use File::Path qw/mkpath/;
25 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
26 use File::Spec qw//;
27 use POSIX qw/strftime/;
28 my $sha1 = qr/[a-f\d]{40}/;
29 my $sha1_short = qr/[a-f\d]{4,40}/;
30 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
31 $_find_copies_harder, $_l, $_version, $_upgrade, $_authors);
32 my (@_branch_from, %tree_map, %users);
34 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
35 'branch|b=s' => \@_branch_from,
36 'authors-file|A=s' => \$_authors );
37 my %cmd = (
38 fetch => [ \&fetch, "Download new revisions from SVN",
39 { 'revision|r=s' => \$_revision, %fc_opts } ],
40 init => [ \&init, "Initialize and fetch (import)", { } ],
41 commit => [ \&commit, "Commit git revisions to SVN",
42 { 'stdin|' => \$_stdin,
43 'edit|e' => \$_edit,
44 'rmdir' => \$_rmdir,
45 'find-copies-harder' => \$_find_copies_harder,
46 'l=i' => \$_l,
47 %fc_opts,
48 } ],
49 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
50 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
51 { 'no-ignore-externals' => \$_no_ignore_ext,
52 'upgrade' => \$_upgrade } ],
54 my $cmd;
55 for (my $i = 0; $i < @ARGV; $i++) {
56 if (defined $cmd{$ARGV[$i]}) {
57 $cmd = $ARGV[$i];
58 splice @ARGV, $i, 1;
59 last;
63 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
65 GetOptions(%opts, 'help|H|h' => \$_help,
66 'version|V' => \$_version,
67 'id|i=s' => \$GIT_SVN) or exit 1;
69 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
70 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
71 $ENV{GIT_DIR} ||= $GIT_DIR;
72 $SVN_URL = undef;
73 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
74 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
76 usage(0) if $_help;
77 version() if $_version;
78 usage(1) unless defined $cmd;
79 load_authors() if $_authors;
80 svn_check_ignore_externals();
81 $cmd{$cmd}->[0]->(@ARGV);
82 exit 0;
84 ####################### primary functions ######################
85 sub usage {
86 my $exit = shift || 0;
87 my $fd = $exit ? \*STDERR : \*STDOUT;
88 print $fd <<"";
89 git-svn - bidirectional operations between a single Subversion tree and git
90 Usage: $0 <command> [options] [arguments]\n
92 print $fd "Available commands:\n" unless $cmd;
94 foreach (sort keys %cmd) {
95 next if $cmd && $cmd ne $_;
96 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
97 foreach (keys %{$cmd{$_}->[2]}) {
98 # prints out arguments as they should be passed:
99 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
100 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
101 "--$_" : "-$_" }
102 split /\|/,$_)," $x\n";
105 print $fd <<"";
106 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
107 arbitrary identifier if you're tracking multiple SVN branches/repositories in
108 one git repository and want to keep them separate. See git-svn(1) for more
109 information.
111 exit $exit;
114 sub version {
115 print "git-svn version $VERSION\n";
116 exit 0;
119 sub rebuild {
120 $SVN_URL = shift or undef;
121 my $newest_rev = 0;
122 if ($_upgrade) {
123 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
124 } else {
125 check_upgrade_needed();
128 my $pid = open(my $rev_list,'-|');
129 defined $pid or croak $!;
130 if ($pid == 0) {
131 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
133 my $latest;
134 while (<$rev_list>) {
135 chomp;
136 my $c = $_;
137 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
138 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
139 next if (!@commit); # skip merges
140 my $id = $commit[$#commit];
141 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
142 \s([a-f\d\-]+)$/x);
143 if (!$rev || !$uuid || !$url) {
144 # some of the original repositories I made had
145 # indentifiers like this:
146 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
147 \@([a-f\d\-]+)/x);
148 if (!$rev || !$uuid) {
149 croak "Unable to extract revision or UUID from ",
150 "$c, $id\n";
154 # if we merged or otherwise started elsewhere, this is
155 # how we break out of it
156 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
157 next if (defined $SVN_URL && ($url ne $SVN_URL));
159 print "r$rev = $c\n";
160 unless (defined $latest) {
161 if (!$SVN_URL && !$url) {
162 croak "SVN repository location required: $url\n";
164 $SVN_URL ||= $url;
165 $SVN_UUID ||= setup_git_svn();
166 $latest = $rev;
168 assert_revision_eq_or_unknown($rev, $c);
169 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
170 $newest_rev = $rev if ($rev > $newest_rev);
172 close $rev_list or croak $?;
173 if (!chdir $SVN_WC) {
174 my @svn_co = ('svn','co',"-r$latest");
175 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
176 sys(@svn_co, $SVN_URL, $SVN_WC);
177 chdir $SVN_WC or croak $!;
180 $pid = fork;
181 defined $pid or croak $!;
182 if ($pid == 0) {
183 my @svn_up = qw(svn up);
184 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
185 sys(@svn_up,"-r$newest_rev");
186 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
187 git_addremove();
188 exec('git-write-tree');
190 waitpid $pid, 0;
192 if ($_upgrade) {
193 print STDERR <<"";
194 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
195 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
200 sub init {
201 $SVN_URL = shift or croak "SVN repository location required\n";
202 unless (-d $GIT_DIR) {
203 sys('git-init-db');
205 setup_git_svn();
208 sub fetch {
209 my (@parents) = @_;
210 check_upgrade_needed();
211 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
212 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
213 unless ($_revision) {
214 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
216 push @log_args, "-r$_revision";
217 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
219 my $svn_log = svn_log_raw(@log_args);
220 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
222 my $base = shift @$svn_log or croak "No base revision!\n";
223 my $last_commit = undef;
224 unless (-d $SVN_WC) {
225 my @svn_co = ('svn','co',"-r$base->{revision}");
226 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
227 sys(@svn_co, $SVN_URL, $SVN_WC);
228 chdir $SVN_WC or croak $!;
229 $last_commit = git_commit($base, @parents);
230 assert_svn_wc_clean($base->{revision}, $last_commit);
231 } else {
232 chdir $SVN_WC or croak $!;
233 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
235 my @svn_up = qw(svn up);
236 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
237 my $last_rev = $base->{revision};
238 foreach my $log_msg (@$svn_log) {
239 assert_svn_wc_clean($last_rev, $last_commit);
240 $last_rev = $log_msg->{revision};
241 sys(@svn_up,"-r$last_rev");
242 $last_commit = git_commit($log_msg, $last_commit, @parents);
244 assert_svn_wc_clean($last_rev, $last_commit);
245 unless (-e "$GIT_DIR/refs/heads/master") {
246 sys(qw(git-update-ref refs/heads/master),$last_commit);
248 return pop @$svn_log;
251 sub commit {
252 my (@commits) = @_;
253 check_upgrade_needed();
254 if ($_stdin || !@commits) {
255 print "Reading from stdin...\n";
256 @commits = ();
257 while (<STDIN>) {
258 if (/\b($sha1_short)\b/o) {
259 unshift @commits, $1;
263 my @revs;
264 foreach my $c (@commits) {
265 chomp(my @tmp = safe_qx('git-rev-parse',$c));
266 if (scalar @tmp == 1) {
267 push @revs, $tmp[0];
268 } elsif (scalar @tmp > 1) {
269 push @revs, reverse (safe_qx('git-rev-list',@tmp));
270 } else {
271 die "Failed to rev-parse $c\n";
274 chomp @revs;
276 fetch();
277 chdir $SVN_WC or croak $!;
278 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
279 foreach my $c (@revs) {
280 my $mods = svn_checkout_tree($svn_current_rev, $c);
281 if (scalar @$mods == 0) {
282 print "Skipping, no changes detected\n";
283 next;
285 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
287 print "Done committing ",scalar @revs," revisions to SVN\n";
291 sub show_ignore {
292 require File::Find or die $!;
293 my $exclude_file = "$GIT_DIR/info/exclude";
294 open my $fh, '<', $exclude_file or croak $!;
295 chomp(my @excludes = (<$fh>));
296 close $fh or croak $!;
298 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
299 chdir $SVN_WC or croak $!;
300 my %ign;
301 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
302 s#^\./##;
303 @{$ign{$_}} = safe_qx(qw(svn propget svn:ignore),$_);
304 }}, no_chdir=>1},'.');
306 print "\n# /\n";
307 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
308 delete $ign{'.'};
309 foreach my $i (sort keys %ign) {
310 print "\n# ",$i,"\n";
311 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
315 ########################### utility functions #########################
317 sub setup_git_svn {
318 defined $SVN_URL or croak "SVN repository location required\n";
319 unless (-d $GIT_DIR) {
320 croak "GIT_DIR=$GIT_DIR does not exist!\n";
322 mkpath(["$GIT_DIR/$GIT_SVN"]);
323 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
324 mkpath([$REV_DIR]);
325 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
326 $SVN_UUID = svn_info($SVN_URL)->{'Repository UUID'} or
327 croak "Repository UUID unreadable\n";
328 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
330 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
331 print $fd '.svn',"\n";
332 close $fd or croak $!;
333 return $SVN_UUID;
336 sub assert_svn_wc_clean {
337 my ($svn_rev, $treeish) = @_;
338 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
339 croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
340 my $lcr = svn_info('.')->{'Last Changed Rev'};
341 if ($svn_rev != $lcr) {
342 print STDERR "Checking for copy-tree ... ";
343 # use
344 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
345 "-r$lcr:$svn_rev")));
346 if (@diff) {
347 croak "Nope! Expected r$svn_rev, got r$lcr\n";
348 } else {
349 print STDERR "OK!\n";
352 my @status = grep(!/^Performing status on external/,(`svn status`));
353 @status = grep(!/^\s*$/,@status);
354 if (scalar @status) {
355 print STDERR "Tree ($SVN_WC) is not clean:\n";
356 print STDERR $_ foreach @status;
357 croak;
359 assert_tree($treeish);
362 sub assert_tree {
363 my ($treeish) = @_;
364 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
365 chomp(my $type = `git-cat-file -t $treeish`);
366 my $expected;
367 while ($type eq 'tag') {
368 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
370 if ($type eq 'commit') {
371 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
372 ($expected) = ($expected =~ /^tree ($sha1)$/);
373 die "Unable to get tree from $treeish\n" unless $expected;
374 } elsif ($type eq 'tree') {
375 $expected = $treeish;
376 } else {
377 die "$treeish is a $type, expected tree, tag or commit\n";
380 my $old_index = $ENV{GIT_INDEX_FILE};
381 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
382 if (-e $tmpindex) {
383 unlink $tmpindex or croak $!;
385 $ENV{GIT_INDEX_FILE} = $tmpindex;
386 git_addremove();
387 chomp(my $tree = `git-write-tree`);
388 if ($old_index) {
389 $ENV{GIT_INDEX_FILE} = $old_index;
390 } else {
391 delete $ENV{GIT_INDEX_FILE};
393 if ($tree ne $expected) {
394 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
398 sub parse_diff_tree {
399 my $diff_fh = shift;
400 local $/ = "\0";
401 my $state = 'meta';
402 my @mods;
403 while (<$diff_fh>) {
404 chomp $_; # this gets rid of the trailing "\0"
405 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
406 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
407 push @mods, { mode_a => $1, mode_b => $2,
408 sha1_b => $3, chg => $4 };
409 if ($4 =~ /^(?:C|R)$/) {
410 $state = 'file_a';
411 } else {
412 $state = 'file_b';
414 } elsif ($state eq 'file_a') {
415 my $x = $mods[$#mods] or croak "Empty array\n";
416 if ($x->{chg} !~ /^(?:C|R)$/) {
417 croak "Error parsing $_, $x->{chg}\n";
419 $x->{file_a} = $_;
420 $state = 'file_b';
421 } elsif ($state eq 'file_b') {
422 my $x = $mods[$#mods] or croak "Empty array\n";
423 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
424 croak "Error parsing $_, $x->{chg}\n";
426 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
427 croak "Error parsing $_, $x->{chg}\n";
429 $x->{file_b} = $_;
430 $state = 'meta';
431 } else {
432 croak "Error parsing $_\n";
435 close $diff_fh or croak $!;
437 return \@mods;
440 sub svn_check_prop_executable {
441 my $m = shift;
442 return if -l $m->{file_b};
443 if ($m->{mode_b} =~ /755$/) {
444 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
445 if ($m->{mode_a} !~ /755$/) {
446 sys(qw(svn propset svn:executable 1), $m->{file_b});
448 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
449 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
450 sys(qw(svn propdel svn:executable), $m->{file_b});
451 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
452 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
456 sub svn_ensure_parent_path {
457 my $dir_b = dirname(shift);
458 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
459 mkpath([$dir_b]) unless (-d $dir_b);
460 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
463 sub precommit_check {
464 my $mods = shift;
465 my (%rm_file, %rmdir_check, %added_check);
467 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
468 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
469 if ($m->{chg} eq 'R') {
470 if (-d $m->{file_b}) {
471 err_dir_to_file("$m->{file_a} => $m->{file_b}");
473 # dir/$file => dir/file/$file
474 my $dirname = dirname($m->{file_b});
475 while ($dirname ne File::Spec->curdir) {
476 if ($dirname ne $m->{file_a}) {
477 $dirname = dirname($dirname);
478 next;
480 err_file_to_dir("$m->{file_a} => $m->{file_b}");
482 # baz/zzz => baz (baz is a file)
483 $dirname = dirname($m->{file_a});
484 while ($dirname ne File::Spec->curdir) {
485 if ($dirname ne $m->{file_b}) {
486 $dirname = dirname($dirname);
487 next;
489 err_dir_to_file("$m->{file_a} => $m->{file_b}");
492 if ($m->{chg} =~ /^(D|R)$/) {
493 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
494 $rm_file{ $m->{$t} } = 1;
495 my $dirname = dirname( $m->{$t} );
496 my $basename = basename( $m->{$t} );
497 $rmdir_check{$dirname}->{$basename} = 1;
498 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
499 if (-d $m->{file_b}) {
500 err_dir_to_file($m->{file_b});
502 my $dirname = dirname( $m->{file_b} );
503 my $basename = basename( $m->{file_b} );
504 $added_check{$dirname}->{$basename} = 1;
505 while ($dirname ne File::Spec->curdir) {
506 if ($rm_file{$dirname}) {
507 err_file_to_dir($m->{file_b});
509 $dirname = dirname $dirname;
513 return (\%rmdir_check, \%added_check);
515 sub err_dir_to_file {
516 my $file = shift;
517 print STDERR "Node change from directory to file ",
518 "is not supported by Subversion: ",$file,"\n";
519 exit 1;
521 sub err_file_to_dir {
522 my $file = shift;
523 print STDERR "Node change from file to directory ",
524 "is not supported by Subversion: ",$file,"\n";
525 exit 1;
529 sub svn_checkout_tree {
530 my ($svn_rev, $treeish) = @_;
531 my $from = file_to_s("$REV_DIR/$svn_rev");
532 assert_svn_wc_clean($svn_rev,$from);
533 print "diff-tree $from $treeish\n";
534 my $pid = open my $diff_fh, '-|';
535 defined $pid or croak $!;
536 if ($pid == 0) {
537 my @diff_tree = qw(git-diff-tree -z -r -C);
538 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
539 push @diff_tree, "-l$_l" if defined $_l;
540 exec(@diff_tree, $from, $treeish) or croak $!;
542 my $mods = parse_diff_tree($diff_fh);
543 unless (@$mods) {
544 # git can do empty commits, but SVN doesn't allow it...
545 return $mods;
547 my ($rm, $add) = precommit_check($mods);
549 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
550 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
551 if ($m->{chg} eq 'C') {
552 svn_ensure_parent_path( $m->{file_b} );
553 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
554 apply_mod_line_blob($m);
555 svn_check_prop_executable($m);
556 } elsif ($m->{chg} eq 'D') {
557 sys(qw(svn rm --force), $m->{file_b});
558 } elsif ($m->{chg} eq 'R') {
559 svn_ensure_parent_path( $m->{file_b} );
560 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
561 apply_mod_line_blob($m);
562 svn_check_prop_executable($m);
563 } elsif ($m->{chg} eq 'M') {
564 apply_mod_line_blob($m);
565 svn_check_prop_executable($m);
566 } elsif ($m->{chg} eq 'T') {
567 sys(qw(svn rm --force),$m->{file_b});
568 apply_mod_line_blob($m);
569 sys(qw(svn add --force), $m->{file_b});
570 svn_check_prop_executable($m);
571 } elsif ($m->{chg} eq 'A') {
572 svn_ensure_parent_path( $m->{file_b} );
573 apply_mod_line_blob($m);
574 sys(qw(svn add --force), $m->{file_b});
575 svn_check_prop_executable($m);
576 } else {
577 croak "Invalid chg: $m->{chg}\n";
581 assert_tree($treeish);
582 if ($_rmdir) { # remove empty directories
583 handle_rmdir($rm, $add);
585 assert_tree($treeish);
586 return $mods;
589 # svn ls doesn't work with respect to the current working tree, but what's
590 # in the repository. There's not even an option for it... *sigh*
591 # (added files don't show up and removed files remain in the ls listing)
592 sub svn_ls_current {
593 my ($dir, $rm, $add) = @_;
594 chomp(my @ls = safe_qx('svn','ls',$dir));
595 my @ret = ();
596 foreach (@ls) {
597 s#/$##; # trailing slashes are evil
598 push @ret, $_ unless $rm->{$dir}->{$_};
600 if (exists $add->{$dir}) {
601 push @ret, keys %{$add->{$dir}};
603 return \@ret;
606 sub handle_rmdir {
607 my ($rm, $add) = @_;
609 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
610 my $ls = svn_ls_current($dir, $rm, $add);
611 next if (scalar @$ls);
612 sys(qw(svn rm --force),$dir);
614 my $dn = dirname $dir;
615 $rm->{ $dn }->{ basename $dir } = 1;
616 $ls = svn_ls_current($dn, $rm, $add);
617 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
618 sys(qw(svn rm --force),$dn);
619 $dir = basename $dn;
620 $dn = dirname $dn;
621 $rm->{ $dn }->{ $dir } = 1;
622 $ls = svn_ls_current($dn, $rm, $add);
627 sub svn_commit_tree {
628 my ($svn_rev, $commit) = @_;
629 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
630 my %log_msg = ( msg => '' );
631 open my $msg, '>', $commit_msg or croak $!;
633 chomp(my $type = `git-cat-file -t $commit`);
634 if ($type eq 'commit') {
635 my $pid = open my $msg_fh, '-|';
636 defined $pid or croak $!;
638 if ($pid == 0) {
639 exec(qw(git-cat-file commit), $commit) or croak $!;
641 my $in_msg = 0;
642 while (<$msg_fh>) {
643 if (!$in_msg) {
644 $in_msg = 1 if (/^\s*$/);
645 } elsif (/^git-svn-id: /) {
646 # skip this, we regenerate the correct one
647 # on re-fetch anyways
648 } else {
649 print $msg $_ or croak $!;
652 close $msg_fh or croak $!;
654 close $msg or croak $!;
656 if ($_edit || ($type eq 'tree')) {
657 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
658 system($editor, $commit_msg);
661 # file_to_s removes all trailing newlines, so just use chomp() here:
662 open $msg, '<', $commit_msg or croak $!;
663 { local $/; chomp($log_msg{msg} = <$msg>); }
664 close $msg or croak $!;
666 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
667 print "Committing $commit: $oneline\n";
669 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
670 my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
671 unlink $commit_msg;
672 defined $committed or croak
673 "Commit output failed to parse committed revision!\n",
674 join("\n",@ci_output),"\n";
675 my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
677 my @svn_up = qw(svn up);
678 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
679 if ($rev_committed == ($svn_rev + 1)) {
680 push @svn_up, "-r$rev_committed";
681 sys(@svn_up);
682 my $info = svn_info('.');
683 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
684 if ($info->{'Last Changed Rev'} != $rev_committed) {
685 croak "$info->{'Last Changed Rev'} != $rev_committed\n"
687 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
688 /(\d{4})\-(\d\d)\-(\d\d)\s
689 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
690 or croak "Failed to parse date: $date\n";
691 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
692 $log_msg{author} = $info->{'Last Changed Author'};
693 $log_msg{revision} = $rev_committed;
694 $log_msg{msg} .= "\n";
695 my $parent = file_to_s("$REV_DIR/$svn_rev");
696 git_commit(\%log_msg, $parent, $commit);
697 return $rev_committed;
699 # resync immediately
700 push @svn_up, "-r$svn_rev";
701 sys(@svn_up);
702 return fetch("$rev_committed=$commit")->{revision};
705 sub svn_log_raw {
706 my (@log_args) = @_;
707 my $pid = open my $log_fh,'-|';
708 defined $pid or croak $!;
710 if ($pid == 0) {
711 exec (qw(svn log), @log_args) or croak $!
714 my @svn_log;
715 my $state = 'sep';
716 while (<$log_fh>) {
717 chomp;
718 if (/^\-{72}$/) {
719 if ($state eq 'msg') {
720 if ($svn_log[$#svn_log]->{lines}) {
721 $svn_log[$#svn_log]->{msg} .= $_."\n";
722 unless(--$svn_log[$#svn_log]->{lines}) {
723 $state = 'sep';
725 } else {
726 croak "Log parse error at: $_\n",
727 $svn_log[$#svn_log]->{revision},
728 "\n";
730 next;
732 if ($state ne 'sep') {
733 croak "Log parse error at: $_\n",
734 "state: $state\n",
735 $svn_log[$#svn_log]->{revision},
736 "\n";
738 $state = 'rev';
740 # if we have an empty log message, put something there:
741 if (@svn_log) {
742 $svn_log[$#svn_log]->{msg} ||= "\n";
743 delete $svn_log[$#svn_log]->{lines};
745 next;
747 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
748 my $rev = $1;
749 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
750 ($lines) = ($lines =~ /(\d+)/);
751 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
752 /(\d{4})\-(\d\d)\-(\d\d)\s
753 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
754 or croak "Failed to parse date: $date\n";
755 my %log_msg = ( revision => $rev,
756 date => "$tz $Y-$m-$d $H:$M:$S",
757 author => $author,
758 lines => $lines,
759 msg => '' );
760 if (defined $_authors && ! defined $users{$author}) {
761 die "Author: $author not defined in ",
762 "$_authors file\n";
764 push @svn_log, \%log_msg;
765 $state = 'msg_start';
766 next;
768 # skip the first blank line of the message:
769 if ($state eq 'msg_start' && /^$/) {
770 $state = 'msg';
771 } elsif ($state eq 'msg') {
772 if ($svn_log[$#svn_log]->{lines}) {
773 $svn_log[$#svn_log]->{msg} .= $_."\n";
774 unless (--$svn_log[$#svn_log]->{lines}) {
775 $state = 'sep';
777 } else {
778 croak "Log parse error at: $_\n",
779 $svn_log[$#svn_log]->{revision},"\n";
783 close $log_fh or croak $?;
784 return \@svn_log;
787 sub svn_info {
788 my $url = shift || $SVN_URL;
790 my $pid = open my $info_fh, '-|';
791 defined $pid or croak $!;
793 if ($pid == 0) {
794 exec(qw(svn info),$url) or croak $!;
797 my $ret = {};
798 # only single-lines seem to exist in svn info output
799 while (<$info_fh>) {
800 chomp $_;
801 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
802 $ret->{$1} = $2;
803 push @{$ret->{-order}}, $1;
806 close $info_fh or croak $!;
807 return $ret;
810 sub sys { system(@_) == 0 or croak $? }
812 sub git_addremove {
813 system( "git-diff-files --name-only -z ".
814 " | git-update-index --remove -z --stdin && ".
815 "git-ls-files -z --others ".
816 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
817 " | git-update-index --add -z --stdin"
818 ) == 0 or croak $?
821 sub s_to_file {
822 my ($str, $file, $mode) = @_;
823 open my $fd,'>',$file or croak $!;
824 print $fd $str,"\n" or croak $!;
825 close $fd or croak $!;
826 chmod ($mode &~ umask, $file) if (defined $mode);
829 sub file_to_s {
830 my $file = shift;
831 open my $fd,'<',$file or croak "$!: file: $file\n";
832 local $/;
833 my $ret = <$fd>;
834 close $fd or croak $!;
835 $ret =~ s/\s*$//s;
836 return $ret;
839 sub assert_revision_unknown {
840 my $revno = shift;
841 if (-f "$REV_DIR/$revno") {
842 croak "$REV_DIR/$revno already exists! ",
843 "Why are we refetching it?";
847 sub assert_revision_eq_or_unknown {
848 my ($revno, $commit) = @_;
849 if (-f "$REV_DIR/$revno") {
850 my $current = file_to_s("$REV_DIR/$revno");
851 if ($commit ne $current) {
852 croak "$REV_DIR/$revno already exists!\n",
853 "current: $current\nexpected: $commit\n";
855 return;
859 sub git_commit {
860 my ($log_msg, @parents) = @_;
861 assert_revision_unknown($log_msg->{revision});
862 my $out_fh = IO::File->new_tmpfile or croak $!;
863 $SVN_UUID ||= svn_info('.')->{'Repository UUID'};
865 map_tree_joins() if (@_branch_from && !%tree_map);
867 # commit parents can be conditionally bound to a particular
868 # svn revision via: "svn_revno=commit_sha1", filter them out here:
869 my @exec_parents;
870 foreach my $p (@parents) {
871 next unless defined $p;
872 if ($p =~ /^(\d+)=($sha1_short)$/o) {
873 if ($1 == $log_msg->{revision}) {
874 push @exec_parents, $2;
876 } else {
877 push @exec_parents, $p if $p =~ /$sha1_short/o;
881 my $pid = fork;
882 defined $pid or croak $!;
883 if ($pid == 0) {
884 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
885 git_addremove();
886 chomp(my $tree = `git-write-tree`);
887 croak if $?;
888 if (exists $tree_map{$tree}) {
889 my %seen_parent = map { $_ => 1 } @exec_parents;
890 foreach (@{$tree_map{$tree}}) {
891 # MAXPARENT is defined to 16 in commit-tree.c:
892 if ($seen_parent{$_} || @exec_parents > 16) {
893 next;
895 push @exec_parents, $_;
896 $seen_parent{$_} = 1;
899 my $msg_fh = IO::File->new_tmpfile or croak $!;
900 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
901 "$SVN_URL\@$log_msg->{revision}",
902 " $SVN_UUID\n" or croak $!;
903 $msg_fh->flush == 0 or croak $!;
904 seek $msg_fh, 0, 0 or croak $!;
906 set_commit_env($log_msg);
908 my @exec = ('git-commit-tree',$tree);
909 push @exec, '-p', $_ foreach @exec_parents;
910 open STDIN, '<&', $msg_fh or croak $!;
911 open STDOUT, '>&', $out_fh or croak $!;
912 exec @exec or croak $!;
914 waitpid($pid,0);
915 croak if $?;
917 $out_fh->flush == 0 or croak $!;
918 seek $out_fh, 0, 0 or croak $!;
919 chomp(my $commit = do { local $/; <$out_fh> });
920 if ($commit !~ /^$sha1$/o) {
921 croak "Failed to commit, invalid sha1: $commit\n";
923 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
924 if (my $primary_parent = shift @exec_parents) {
925 push @update_ref, $primary_parent;
927 sys(@update_ref);
928 sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
929 print "r$log_msg->{revision} = $commit\n";
930 return $commit;
933 sub set_commit_env {
934 my ($log_msg) = @_;
935 my $author = $log_msg->{author};
936 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
937 : ($author,"$author\@$SVN_UUID");
938 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
939 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
940 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
943 sub apply_mod_line_blob {
944 my $m = shift;
945 if ($m->{mode_b} =~ /^120/) {
946 blob_to_symlink($m->{sha1_b}, $m->{file_b});
947 } else {
948 blob_to_file($m->{sha1_b}, $m->{file_b});
952 sub blob_to_symlink {
953 my ($blob, $link) = @_;
954 defined $link or croak "\$link not defined!\n";
955 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
956 if (-l $link || -f _) {
957 unlink $link or croak $!;
960 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
961 symlink $dest, $link or croak $!;
964 sub blob_to_file {
965 my ($blob, $file) = @_;
966 defined $file or croak "\$file not defined!\n";
967 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
968 if (-l $file || -f _) {
969 unlink $file or croak $!;
972 open my $blob_fh, '>', $file or croak "$!: $file\n";
973 my $pid = fork;
974 defined $pid or croak $!;
976 if ($pid == 0) {
977 open STDOUT, '>&', $blob_fh or croak $!;
978 exec('git-cat-file','blob',$blob);
980 waitpid $pid, 0;
981 croak $? if $?;
983 close $blob_fh or croak $!;
986 sub safe_qx {
987 my $pid = open my $child, '-|';
988 defined $pid or croak $!;
989 if ($pid == 0) {
990 exec(@_) or croak $?;
992 my @ret = (<$child>);
993 close $child or croak $?;
994 die $? if $?; # just in case close didn't error out
995 return wantarray ? @ret : join('',@ret);
998 sub svn_check_ignore_externals {
999 return if $_no_ignore_ext;
1000 unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
1001 print STDERR "W: Installed svn version does not support ",
1002 "--ignore-externals\n";
1003 $_no_ignore_ext = 1;
1007 sub check_upgrade_needed {
1008 my $old = eval {
1009 my $pid = open my $child, '-|';
1010 defined $pid or croak $!;
1011 if ($pid == 0) {
1012 close STDERR;
1013 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1015 my @ret = (<$child>);
1016 close $child or croak $?;
1017 die $? if $?; # just in case close didn't error out
1018 return wantarray ? @ret : join('',@ret);
1020 return unless $old;
1021 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1022 if ($@ || !$head) {
1023 print STDERR "Please run: $0 rebuild --upgrade\n";
1024 exit 1;
1028 # fills %tree_map with a reverse mapping of trees to commits. Useful
1029 # for finding parents to commit on.
1030 sub map_tree_joins {
1031 foreach my $br (@_branch_from) {
1032 my $pid = open my $pipe, '-|';
1033 defined $pid or croak $!;
1034 if ($pid == 0) {
1035 exec(qw(git-rev-list --pretty=raw), $br) or croak $?;
1037 while (<$pipe>) {
1038 if (/^commit ($sha1)$/o) {
1039 my $commit = $1;
1040 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1041 unless (defined $tree) {
1042 die "Failed to parse commit $commit\n";
1044 push @{$tree_map{$tree}}, $commit;
1047 close $pipe or croak $?;
1051 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1052 sub load_authors {
1053 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1054 while (<$authors>) {
1055 chomp;
1056 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1057 my ($user, $name, $email) = ($1, $2, $3);
1058 $users{$user} = [$name, $email];
1060 close $authors or croak $!;
1063 __END__
1065 Data structures:
1067 @svn_log = array of log_msg hashes
1069 $log_msg hash
1071 msg => 'whitespace-formatted log entry
1072 ', # trailing newline is preserved
1073 revision => '8', # integer
1074 date => '2004-02-24T17:01:44.108345Z', # commit date
1075 author => 'committer name'
1079 @mods = array of diff-index line hashes, each element represents one line
1080 of diff-index output
1082 diff-index line ($m hash)
1084 mode_a => first column of diff-index output, no leading ':',
1085 mode_b => second column of diff-index output,
1086 sha1_b => sha1sum of the final blob,
1087 chg => change type [MCRADT],
1088 file_a => original file name of a file (iff chg is 'C' or 'R')
1089 file_b => new/current file name of a file (any chg)