contrib/git-svn: fix svn compat and fetch args
[git/debian.git] / contrib / git-svn / git-svn.perl
blobdca4e5c412ed762c6374442a29c2843d886e653f
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);
33 my $_svn_co_url_revs;
35 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
36 'branch|b=s' => \@_branch_from,
37 'authors-file|A=s' => \$_authors );
38 my %cmd = (
39 fetch => [ \&fetch, "Download new revisions from SVN",
40 { 'revision|r=s' => \$_revision, %fc_opts } ],
41 init => [ \&init, "Initialize and fetch (import)", { } ],
42 commit => [ \&commit, "Commit git revisions to SVN",
43 { 'stdin|' => \$_stdin,
44 'edit|e' => \$_edit,
45 'rmdir' => \$_rmdir,
46 'find-copies-harder' => \$_find_copies_harder,
47 'l=i' => \$_l,
48 %fc_opts,
49 } ],
50 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
51 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
52 { 'no-ignore-externals' => \$_no_ignore_ext,
53 'upgrade' => \$_upgrade } ],
55 my $cmd;
56 for (my $i = 0; $i < @ARGV; $i++) {
57 if (defined $cmd{$ARGV[$i]}) {
58 $cmd = $ARGV[$i];
59 splice @ARGV, $i, 1;
60 last;
64 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
66 GetOptions(%opts, 'help|H|h' => \$_help,
67 'version|V' => \$_version,
68 'id|i=s' => \$GIT_SVN) or exit 1;
70 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
71 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
72 $ENV{GIT_DIR} ||= $GIT_DIR;
73 $SVN_URL = undef;
74 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
75 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
77 usage(0) if $_help;
78 version() if $_version;
79 usage(1) unless defined $cmd;
80 load_authors() if $_authors;
81 svn_compat_check();
82 $cmd{$cmd}->[0]->(@ARGV);
83 exit 0;
85 ####################### primary functions ######################
86 sub usage {
87 my $exit = shift || 0;
88 my $fd = $exit ? \*STDERR : \*STDOUT;
89 print $fd <<"";
90 git-svn - bidirectional operations between a single Subversion tree and git
91 Usage: $0 <command> [options] [arguments]\n
93 print $fd "Available commands:\n" unless $cmd;
95 foreach (sort keys %cmd) {
96 next if $cmd && $cmd ne $_;
97 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
98 foreach (keys %{$cmd{$_}->[2]}) {
99 # prints out arguments as they should be passed:
100 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
101 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
102 "--$_" : "-$_" }
103 split /\|/,$_)," $x\n";
106 print $fd <<"";
107 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
108 arbitrary identifier if you're tracking multiple SVN branches/repositories in
109 one git repository and want to keep them separate. See git-svn(1) for more
110 information.
112 exit $exit;
115 sub version {
116 print "git-svn version $VERSION\n";
117 exit 0;
120 sub rebuild {
121 $SVN_URL = shift or undef;
122 my $newest_rev = 0;
123 if ($_upgrade) {
124 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
125 } else {
126 check_upgrade_needed();
129 my $pid = open(my $rev_list,'-|');
130 defined $pid or croak $!;
131 if ($pid == 0) {
132 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
134 my $latest;
135 while (<$rev_list>) {
136 chomp;
137 my $c = $_;
138 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
139 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
140 next if (!@commit); # skip merges
141 my $id = $commit[$#commit];
142 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
143 \s([a-f\d\-]+)$/x);
144 if (!$rev || !$uuid || !$url) {
145 # some of the original repositories I made had
146 # indentifiers like this:
147 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
148 \@([a-f\d\-]+)/x);
149 if (!$rev || !$uuid) {
150 croak "Unable to extract revision or UUID from ",
151 "$c, $id\n";
155 # if we merged or otherwise started elsewhere, this is
156 # how we break out of it
157 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
158 next if (defined $SVN_URL && ($url ne $SVN_URL));
160 print "r$rev = $c\n";
161 unless (defined $latest) {
162 if (!$SVN_URL && !$url) {
163 croak "SVN repository location required: $url\n";
165 $SVN_URL ||= $url;
166 $SVN_UUID ||= $uuid;
167 setup_git_svn();
168 $latest = $rev;
170 assert_revision_eq_or_unknown($rev, $c);
171 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
172 $newest_rev = $rev if ($rev > $newest_rev);
174 close $rev_list or croak $?;
175 if (!chdir $SVN_WC) {
176 svn_cmd_checkout($SVN_URL, $latest, $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 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
226 chdir $SVN_WC or croak $!;
227 read_uuid();
228 $last_commit = git_commit($base, @parents);
229 assert_svn_wc_clean($base->{revision}, $last_commit);
230 } else {
231 chdir $SVN_WC or croak $!;
232 read_uuid();
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 $info = svn_info('.');
279 read_uuid($info);
280 my $svn_current_rev = $info->{'Last Changed Rev'};
281 foreach my $c (@revs) {
282 my $mods = svn_checkout_tree($svn_current_rev, $c);
283 if (scalar @$mods == 0) {
284 print "Skipping, no changes detected\n";
285 next;
287 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
289 print "Done committing ",scalar @revs," revisions to SVN\n";
293 sub show_ignore {
294 require File::Find or die $!;
295 my $exclude_file = "$GIT_DIR/info/exclude";
296 open my $fh, '<', $exclude_file or croak $!;
297 chomp(my @excludes = (<$fh>));
298 close $fh or croak $!;
300 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
301 chdir $SVN_WC or croak $!;
302 my %ign;
303 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
304 s#^\./##;
305 @{$ign{$_}} = safe_qx(qw(svn propget svn:ignore),$_);
306 }}, no_chdir=>1},'.');
308 print "\n# /\n";
309 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
310 delete $ign{'.'};
311 foreach my $i (sort keys %ign) {
312 print "\n# ",$i,"\n";
313 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
317 ########################### utility functions #########################
319 sub read_uuid {
320 return if $SVN_UUID;
321 my $info = shift || svn_info('.');
322 $SVN_UUID = $info->{'Repository UUID'} or
323 croak "Repository UUID unreadable\n";
324 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
327 sub setup_git_svn {
328 defined $SVN_URL or croak "SVN repository location required\n";
329 unless (-d $GIT_DIR) {
330 croak "GIT_DIR=$GIT_DIR does not exist!\n";
332 mkpath(["$GIT_DIR/$GIT_SVN"]);
333 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
334 mkpath([$REV_DIR]);
335 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
337 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
338 print $fd '.svn',"\n";
339 close $fd or croak $!;
342 sub assert_svn_wc_clean {
343 my ($svn_rev, $treeish) = @_;
344 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
345 croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
346 my $lcr = svn_info('.')->{'Last Changed Rev'};
347 if ($svn_rev != $lcr) {
348 print STDERR "Checking for copy-tree ... ";
349 # use
350 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
351 "-r$lcr:$svn_rev")));
352 if (@diff) {
353 croak "Nope! Expected r$svn_rev, got r$lcr\n";
354 } else {
355 print STDERR "OK!\n";
358 my @status = grep(!/^Performing status on external/,(`svn status`));
359 @status = grep(!/^\s*$/,@status);
360 if (scalar @status) {
361 print STDERR "Tree ($SVN_WC) is not clean:\n";
362 print STDERR $_ foreach @status;
363 croak;
365 assert_tree($treeish);
368 sub assert_tree {
369 my ($treeish) = @_;
370 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
371 chomp(my $type = `git-cat-file -t $treeish`);
372 my $expected;
373 while ($type eq 'tag') {
374 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
376 if ($type eq 'commit') {
377 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
378 ($expected) = ($expected =~ /^tree ($sha1)$/);
379 die "Unable to get tree from $treeish\n" unless $expected;
380 } elsif ($type eq 'tree') {
381 $expected = $treeish;
382 } else {
383 die "$treeish is a $type, expected tree, tag or commit\n";
386 my $old_index = $ENV{GIT_INDEX_FILE};
387 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
388 if (-e $tmpindex) {
389 unlink $tmpindex or croak $!;
391 $ENV{GIT_INDEX_FILE} = $tmpindex;
392 git_addremove();
393 chomp(my $tree = `git-write-tree`);
394 if ($old_index) {
395 $ENV{GIT_INDEX_FILE} = $old_index;
396 } else {
397 delete $ENV{GIT_INDEX_FILE};
399 if ($tree ne $expected) {
400 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
404 sub parse_diff_tree {
405 my $diff_fh = shift;
406 local $/ = "\0";
407 my $state = 'meta';
408 my @mods;
409 while (<$diff_fh>) {
410 chomp $_; # this gets rid of the trailing "\0"
411 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
412 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
413 push @mods, { mode_a => $1, mode_b => $2,
414 sha1_b => $3, chg => $4 };
415 if ($4 =~ /^(?:C|R)$/) {
416 $state = 'file_a';
417 } else {
418 $state = 'file_b';
420 } elsif ($state eq 'file_a') {
421 my $x = $mods[$#mods] or croak "Empty array\n";
422 if ($x->{chg} !~ /^(?:C|R)$/) {
423 croak "Error parsing $_, $x->{chg}\n";
425 $x->{file_a} = $_;
426 $state = 'file_b';
427 } elsif ($state eq 'file_b') {
428 my $x = $mods[$#mods] or croak "Empty array\n";
429 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
430 croak "Error parsing $_, $x->{chg}\n";
432 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
433 croak "Error parsing $_, $x->{chg}\n";
435 $x->{file_b} = $_;
436 $state = 'meta';
437 } else {
438 croak "Error parsing $_\n";
441 close $diff_fh or croak $!;
443 return \@mods;
446 sub svn_check_prop_executable {
447 my $m = shift;
448 return if -l $m->{file_b};
449 if ($m->{mode_b} =~ /755$/) {
450 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
451 if ($m->{mode_a} !~ /755$/) {
452 sys(qw(svn propset svn:executable 1), $m->{file_b});
454 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
455 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
456 sys(qw(svn propdel svn:executable), $m->{file_b});
457 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
458 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
462 sub svn_ensure_parent_path {
463 my $dir_b = dirname(shift);
464 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
465 mkpath([$dir_b]) unless (-d $dir_b);
466 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
469 sub precommit_check {
470 my $mods = shift;
471 my (%rm_file, %rmdir_check, %added_check);
473 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
474 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
475 if ($m->{chg} eq 'R') {
476 if (-d $m->{file_b}) {
477 err_dir_to_file("$m->{file_a} => $m->{file_b}");
479 # dir/$file => dir/file/$file
480 my $dirname = dirname($m->{file_b});
481 while ($dirname ne File::Spec->curdir) {
482 if ($dirname ne $m->{file_a}) {
483 $dirname = dirname($dirname);
484 next;
486 err_file_to_dir("$m->{file_a} => $m->{file_b}");
488 # baz/zzz => baz (baz is a file)
489 $dirname = dirname($m->{file_a});
490 while ($dirname ne File::Spec->curdir) {
491 if ($dirname ne $m->{file_b}) {
492 $dirname = dirname($dirname);
493 next;
495 err_dir_to_file("$m->{file_a} => $m->{file_b}");
498 if ($m->{chg} =~ /^(D|R)$/) {
499 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
500 $rm_file{ $m->{$t} } = 1;
501 my $dirname = dirname( $m->{$t} );
502 my $basename = basename( $m->{$t} );
503 $rmdir_check{$dirname}->{$basename} = 1;
504 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
505 if (-d $m->{file_b}) {
506 err_dir_to_file($m->{file_b});
508 my $dirname = dirname( $m->{file_b} );
509 my $basename = basename( $m->{file_b} );
510 $added_check{$dirname}->{$basename} = 1;
511 while ($dirname ne File::Spec->curdir) {
512 if ($rm_file{$dirname}) {
513 err_file_to_dir($m->{file_b});
515 $dirname = dirname $dirname;
519 return (\%rmdir_check, \%added_check);
521 sub err_dir_to_file {
522 my $file = shift;
523 print STDERR "Node change from directory to file ",
524 "is not supported by Subversion: ",$file,"\n";
525 exit 1;
527 sub err_file_to_dir {
528 my $file = shift;
529 print STDERR "Node change from file to directory ",
530 "is not supported by Subversion: ",$file,"\n";
531 exit 1;
535 sub svn_checkout_tree {
536 my ($svn_rev, $treeish) = @_;
537 my $from = file_to_s("$REV_DIR/$svn_rev");
538 assert_svn_wc_clean($svn_rev,$from);
539 print "diff-tree $from $treeish\n";
540 my $pid = open my $diff_fh, '-|';
541 defined $pid or croak $!;
542 if ($pid == 0) {
543 my @diff_tree = qw(git-diff-tree -z -r -C);
544 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
545 push @diff_tree, "-l$_l" if defined $_l;
546 exec(@diff_tree, $from, $treeish) or croak $!;
548 my $mods = parse_diff_tree($diff_fh);
549 unless (@$mods) {
550 # git can do empty commits, but SVN doesn't allow it...
551 return $mods;
553 my ($rm, $add) = precommit_check($mods);
555 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
556 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
557 if ($m->{chg} eq 'C') {
558 svn_ensure_parent_path( $m->{file_b} );
559 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
560 apply_mod_line_blob($m);
561 svn_check_prop_executable($m);
562 } elsif ($m->{chg} eq 'D') {
563 sys(qw(svn rm --force), $m->{file_b});
564 } elsif ($m->{chg} eq 'R') {
565 svn_ensure_parent_path( $m->{file_b} );
566 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
567 apply_mod_line_blob($m);
568 svn_check_prop_executable($m);
569 } elsif ($m->{chg} eq 'M') {
570 apply_mod_line_blob($m);
571 svn_check_prop_executable($m);
572 } elsif ($m->{chg} eq 'T') {
573 sys(qw(svn rm --force),$m->{file_b});
574 apply_mod_line_blob($m);
575 sys(qw(svn add --force), $m->{file_b});
576 svn_check_prop_executable($m);
577 } elsif ($m->{chg} eq 'A') {
578 svn_ensure_parent_path( $m->{file_b} );
579 apply_mod_line_blob($m);
580 sys(qw(svn add --force), $m->{file_b});
581 svn_check_prop_executable($m);
582 } else {
583 croak "Invalid chg: $m->{chg}\n";
587 assert_tree($treeish);
588 if ($_rmdir) { # remove empty directories
589 handle_rmdir($rm, $add);
591 assert_tree($treeish);
592 return $mods;
595 # svn ls doesn't work with respect to the current working tree, but what's
596 # in the repository. There's not even an option for it... *sigh*
597 # (added files don't show up and removed files remain in the ls listing)
598 sub svn_ls_current {
599 my ($dir, $rm, $add) = @_;
600 chomp(my @ls = safe_qx('svn','ls',$dir));
601 my @ret = ();
602 foreach (@ls) {
603 s#/$##; # trailing slashes are evil
604 push @ret, $_ unless $rm->{$dir}->{$_};
606 if (exists $add->{$dir}) {
607 push @ret, keys %{$add->{$dir}};
609 return \@ret;
612 sub handle_rmdir {
613 my ($rm, $add) = @_;
615 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
616 my $ls = svn_ls_current($dir, $rm, $add);
617 next if (scalar @$ls);
618 sys(qw(svn rm --force),$dir);
620 my $dn = dirname $dir;
621 $rm->{ $dn }->{ basename $dir } = 1;
622 $ls = svn_ls_current($dn, $rm, $add);
623 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
624 sys(qw(svn rm --force),$dn);
625 $dir = basename $dn;
626 $dn = dirname $dn;
627 $rm->{ $dn }->{ $dir } = 1;
628 $ls = svn_ls_current($dn, $rm, $add);
633 sub svn_commit_tree {
634 my ($svn_rev, $commit) = @_;
635 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
636 my %log_msg = ( msg => '' );
637 open my $msg, '>', $commit_msg or croak $!;
639 chomp(my $type = `git-cat-file -t $commit`);
640 if ($type eq 'commit') {
641 my $pid = open my $msg_fh, '-|';
642 defined $pid or croak $!;
644 if ($pid == 0) {
645 exec(qw(git-cat-file commit), $commit) or croak $!;
647 my $in_msg = 0;
648 while (<$msg_fh>) {
649 if (!$in_msg) {
650 $in_msg = 1 if (/^\s*$/);
651 } elsif (/^git-svn-id: /) {
652 # skip this, we regenerate the correct one
653 # on re-fetch anyways
654 } else {
655 print $msg $_ or croak $!;
658 close $msg_fh or croak $!;
660 close $msg or croak $!;
662 if ($_edit || ($type eq 'tree')) {
663 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
664 system($editor, $commit_msg);
667 # file_to_s removes all trailing newlines, so just use chomp() here:
668 open $msg, '<', $commit_msg or croak $!;
669 { local $/; chomp($log_msg{msg} = <$msg>); }
670 close $msg or croak $!;
672 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
673 print "Committing $commit: $oneline\n";
675 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
676 my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
677 unlink $commit_msg;
678 defined $committed or croak
679 "Commit output failed to parse committed revision!\n",
680 join("\n",@ci_output),"\n";
681 my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
683 my @svn_up = qw(svn up);
684 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
685 if ($rev_committed == ($svn_rev + 1)) {
686 push @svn_up, "-r$rev_committed";
687 sys(@svn_up);
688 my $info = svn_info('.');
689 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
690 if ($info->{'Last Changed Rev'} != $rev_committed) {
691 croak "$info->{'Last Changed Rev'} != $rev_committed\n"
693 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
694 /(\d{4})\-(\d\d)\-(\d\d)\s
695 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
696 or croak "Failed to parse date: $date\n";
697 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
698 $log_msg{author} = $info->{'Last Changed Author'};
699 $log_msg{revision} = $rev_committed;
700 $log_msg{msg} .= "\n";
701 my $parent = file_to_s("$REV_DIR/$svn_rev");
702 git_commit(\%log_msg, $parent, $commit);
703 return $rev_committed;
705 # resync immediately
706 push @svn_up, "-r$svn_rev";
707 sys(@svn_up);
708 return fetch("$rev_committed=$commit")->{revision};
711 sub svn_log_raw {
712 my (@log_args) = @_;
713 my $pid = open my $log_fh,'-|';
714 defined $pid or croak $!;
716 if ($pid == 0) {
717 exec (qw(svn log), @log_args) or croak $!
720 my @svn_log;
721 my $state = 'sep';
722 while (<$log_fh>) {
723 chomp;
724 if (/^\-{72}$/) {
725 if ($state eq 'msg') {
726 if ($svn_log[$#svn_log]->{lines}) {
727 $svn_log[$#svn_log]->{msg} .= $_."\n";
728 unless(--$svn_log[$#svn_log]->{lines}) {
729 $state = 'sep';
731 } else {
732 croak "Log parse error at: $_\n",
733 $svn_log[$#svn_log]->{revision},
734 "\n";
736 next;
738 if ($state ne 'sep') {
739 croak "Log parse error at: $_\n",
740 "state: $state\n",
741 $svn_log[$#svn_log]->{revision},
742 "\n";
744 $state = 'rev';
746 # if we have an empty log message, put something there:
747 if (@svn_log) {
748 $svn_log[$#svn_log]->{msg} ||= "\n";
749 delete $svn_log[$#svn_log]->{lines};
751 next;
753 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
754 my $rev = $1;
755 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
756 ($lines) = ($lines =~ /(\d+)/);
757 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
758 /(\d{4})\-(\d\d)\-(\d\d)\s
759 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
760 or croak "Failed to parse date: $date\n";
761 my %log_msg = ( revision => $rev,
762 date => "$tz $Y-$m-$d $H:$M:$S",
763 author => $author,
764 lines => $lines,
765 msg => '' );
766 if (defined $_authors && ! defined $users{$author}) {
767 die "Author: $author not defined in ",
768 "$_authors file\n";
770 push @svn_log, \%log_msg;
771 $state = 'msg_start';
772 next;
774 # skip the first blank line of the message:
775 if ($state eq 'msg_start' && /^$/) {
776 $state = 'msg';
777 } elsif ($state eq 'msg') {
778 if ($svn_log[$#svn_log]->{lines}) {
779 $svn_log[$#svn_log]->{msg} .= $_."\n";
780 unless (--$svn_log[$#svn_log]->{lines}) {
781 $state = 'sep';
783 } else {
784 croak "Log parse error at: $_\n",
785 $svn_log[$#svn_log]->{revision},"\n";
789 close $log_fh or croak $?;
790 return \@svn_log;
793 sub svn_info {
794 my $url = shift || $SVN_URL;
796 my $pid = open my $info_fh, '-|';
797 defined $pid or croak $!;
799 if ($pid == 0) {
800 exec(qw(svn info),$url) or croak $!;
803 my $ret = {};
804 # only single-lines seem to exist in svn info output
805 while (<$info_fh>) {
806 chomp $_;
807 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
808 $ret->{$1} = $2;
809 push @{$ret->{-order}}, $1;
812 close $info_fh or croak $!;
813 return $ret;
816 sub sys { system(@_) == 0 or croak $? }
818 sub git_addremove {
819 system( "git-diff-files --name-only -z ".
820 " | git-update-index --remove -z --stdin && ".
821 "git-ls-files -z --others ".
822 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
823 " | git-update-index --add -z --stdin"
824 ) == 0 or croak $?
827 sub s_to_file {
828 my ($str, $file, $mode) = @_;
829 open my $fd,'>',$file or croak $!;
830 print $fd $str,"\n" or croak $!;
831 close $fd or croak $!;
832 chmod ($mode &~ umask, $file) if (defined $mode);
835 sub file_to_s {
836 my $file = shift;
837 open my $fd,'<',$file or croak "$!: file: $file\n";
838 local $/;
839 my $ret = <$fd>;
840 close $fd or croak $!;
841 $ret =~ s/\s*$//s;
842 return $ret;
845 sub assert_revision_unknown {
846 my $revno = shift;
847 if (-f "$REV_DIR/$revno") {
848 croak "$REV_DIR/$revno already exists! ",
849 "Why are we refetching it?";
853 sub assert_revision_eq_or_unknown {
854 my ($revno, $commit) = @_;
855 if (-f "$REV_DIR/$revno") {
856 my $current = file_to_s("$REV_DIR/$revno");
857 if ($commit ne $current) {
858 croak "$REV_DIR/$revno already exists!\n",
859 "current: $current\nexpected: $commit\n";
861 return;
865 sub git_commit {
866 my ($log_msg, @parents) = @_;
867 assert_revision_unknown($log_msg->{revision});
868 my $out_fh = IO::File->new_tmpfile or croak $!;
870 map_tree_joins() if (@_branch_from && !%tree_map);
872 # commit parents can be conditionally bound to a particular
873 # svn revision via: "svn_revno=commit_sha1", filter them out here:
874 my @exec_parents;
875 foreach my $p (@parents) {
876 next unless defined $p;
877 if ($p =~ /^(\d+)=($sha1_short)$/o) {
878 if ($1 == $log_msg->{revision}) {
879 push @exec_parents, $2;
881 } else {
882 push @exec_parents, $p if $p =~ /$sha1_short/o;
886 my $pid = fork;
887 defined $pid or croak $!;
888 if ($pid == 0) {
889 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
890 git_addremove();
891 chomp(my $tree = `git-write-tree`);
892 croak if $?;
893 if (exists $tree_map{$tree}) {
894 my %seen_parent = map { $_ => 1 } @exec_parents;
895 foreach (@{$tree_map{$tree}}) {
896 # MAXPARENT is defined to 16 in commit-tree.c:
897 if ($seen_parent{$_} || @exec_parents > 16) {
898 next;
900 push @exec_parents, $_;
901 $seen_parent{$_} = 1;
904 my $msg_fh = IO::File->new_tmpfile or croak $!;
905 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
906 "$SVN_URL\@$log_msg->{revision}",
907 " $SVN_UUID\n" or croak $!;
908 $msg_fh->flush == 0 or croak $!;
909 seek $msg_fh, 0, 0 or croak $!;
911 set_commit_env($log_msg);
913 my @exec = ('git-commit-tree',$tree);
914 push @exec, '-p', $_ foreach @exec_parents;
915 open STDIN, '<&', $msg_fh or croak $!;
916 open STDOUT, '>&', $out_fh or croak $!;
917 exec @exec or croak $!;
919 waitpid($pid,0);
920 croak if $?;
922 $out_fh->flush == 0 or croak $!;
923 seek $out_fh, 0, 0 or croak $!;
924 chomp(my $commit = do { local $/; <$out_fh> });
925 if ($commit !~ /^$sha1$/o) {
926 croak "Failed to commit, invalid sha1: $commit\n";
928 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
929 if (my $primary_parent = shift @exec_parents) {
930 $pid = fork;
931 defined $pid or croak $!;
932 if (!$pid) {
933 close STDERR;
934 close STDOUT;
935 exec 'git-rev-parse','--verify',
936 "refs/remotes/$GIT_SVN^0";
938 waitpid $pid, 0;
939 push @update_ref, $primary_parent unless $?;
941 sys(@update_ref);
942 sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
943 print "r$log_msg->{revision} = $commit\n";
944 return $commit;
947 sub set_commit_env {
948 my ($log_msg) = @_;
949 my $author = $log_msg->{author};
950 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
951 : ($author,"$author\@$SVN_UUID");
952 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
953 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
954 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
957 sub apply_mod_line_blob {
958 my $m = shift;
959 if ($m->{mode_b} =~ /^120/) {
960 blob_to_symlink($m->{sha1_b}, $m->{file_b});
961 } else {
962 blob_to_file($m->{sha1_b}, $m->{file_b});
966 sub blob_to_symlink {
967 my ($blob, $link) = @_;
968 defined $link or croak "\$link not defined!\n";
969 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
970 if (-l $link || -f _) {
971 unlink $link or croak $!;
974 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
975 symlink $dest, $link or croak $!;
978 sub blob_to_file {
979 my ($blob, $file) = @_;
980 defined $file or croak "\$file not defined!\n";
981 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
982 if (-l $file || -f _) {
983 unlink $file or croak $!;
986 open my $blob_fh, '>', $file or croak "$!: $file\n";
987 my $pid = fork;
988 defined $pid or croak $!;
990 if ($pid == 0) {
991 open STDOUT, '>&', $blob_fh or croak $!;
992 exec('git-cat-file','blob',$blob);
994 waitpid $pid, 0;
995 croak $? if $?;
997 close $blob_fh or croak $!;
1000 sub safe_qx {
1001 my $pid = open my $child, '-|';
1002 defined $pid or croak $!;
1003 if ($pid == 0) {
1004 exec(@_) or croak $?;
1006 my @ret = (<$child>);
1007 close $child or croak $?;
1008 die $? if $?; # just in case close didn't error out
1009 return wantarray ? @ret : join('',@ret);
1012 sub svn_compat_check {
1013 my @co_help = safe_qx(qw(svn co -h));
1014 unless (grep /ignore-externals/,@co_help) {
1015 print STDERR "W: Installed svn version does not support ",
1016 "--ignore-externals\n";
1017 $_no_ignore_ext = 1;
1019 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1020 $_svn_co_url_revs = 1;
1024 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1025 # (and they won't honor URL@<rev> without -r<rev>, too!)
1026 sub svn_cmd_checkout {
1027 my ($url, $rev, $dir) = @_;
1028 my @cmd = ('svn','co', "-r$rev");
1029 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1030 $url .= "\@$rev" if $_svn_co_url_revs;
1031 sys(@cmd, $url, $dir);
1034 sub check_upgrade_needed {
1035 my $old = eval {
1036 my $pid = open my $child, '-|';
1037 defined $pid or croak $!;
1038 if ($pid == 0) {
1039 close STDERR;
1040 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1042 my @ret = (<$child>);
1043 close $child or croak $?;
1044 die $? if $?; # just in case close didn't error out
1045 return wantarray ? @ret : join('',@ret);
1047 return unless $old;
1048 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1049 if ($@ || !$head) {
1050 print STDERR "Please run: $0 rebuild --upgrade\n";
1051 exit 1;
1055 # fills %tree_map with a reverse mapping of trees to commits. Useful
1056 # for finding parents to commit on.
1057 sub map_tree_joins {
1058 foreach my $br (@_branch_from) {
1059 my $pid = open my $pipe, '-|';
1060 defined $pid or croak $!;
1061 if ($pid == 0) {
1062 exec(qw(git-rev-list --pretty=raw), $br) or croak $?;
1064 while (<$pipe>) {
1065 if (/^commit ($sha1)$/o) {
1066 my $commit = $1;
1067 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1068 unless (defined $tree) {
1069 die "Failed to parse commit $commit\n";
1071 push @{$tree_map{$tree}}, $commit;
1074 close $pipe or croak $?;
1078 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1079 sub load_authors {
1080 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1081 while (<$authors>) {
1082 chomp;
1083 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1084 my ($user, $name, $email) = ($1, $2, $3);
1085 $users{$user} = [$name, $email];
1087 close $authors or croak $!;
1090 __END__
1092 Data structures:
1094 @svn_log = array of log_msg hashes
1096 $log_msg hash
1098 msg => 'whitespace-formatted log entry
1099 ', # trailing newline is preserved
1100 revision => '8', # integer
1101 date => '2004-02-24T17:01:44.108345Z', # commit date
1102 author => 'committer name'
1106 @mods = array of diff-index line hashes, each element represents one line
1107 of diff-index output
1109 diff-index line ($m hash)
1111 mode_a => first column of diff-index output, no leading ':',
1112 mode_b => second column of diff-index output,
1113 sha1_b => sha1sum of the final blob,
1114 chg => change type [MCRADT],
1115 file_a => original file name of a file (iff chg is 'C' or 'R')
1116 file_b => new/current file name of a file (any chg)