3a5945490e4665133f1a4898608f20d3ce363f0c
[git.git] / contrib / git-svn / git-svn
1 #!/usr/bin/env perl
2 use warnings;
3 use strict;
4 use vars qw/    $AUTHOR $VERSION
5                 $SVN_URL $SVN_INFO $SVN_WC
6                 $GIT_SVN_INDEX $GIT_SVN
7                 $GIT_DIR $REV_DIR/;
8 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
9 $VERSION = '0.9.0';
10 $GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
11 $GIT_SVN = $ENV{GIT_SVN_ID} || 'git-svn';
12 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
13 $ENV{GIT_DIR} ||= $GIT_DIR;
14 $SVN_URL = undef;
15 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
16 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
17
18 # make sure the svn binary gives consistent output between locales and TZs:
19 $ENV{TZ} = 'UTC';
20 $ENV{LC_ALL} = 'C';
21
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 use Carp qw/croak/;
26 use IO::File qw//;
27 use File::Basename qw/dirname basename/;
28 use File::Path qw/mkpath/;
29 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
30 use File::Spec qw//;
31 my $sha1 = qr/[a-f\d]{40}/;
32 my $sha1_short = qr/[a-f\d]{6,40}/;
33 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
34         $_find_copies_harder, $_l);
35
36 GetOptions(     'revision|r=s' => \$_revision,
37                 'no-ignore-externals' => \$_no_ignore_ext,
38                 'stdin|' => \$_stdin,
39                 'edit|e' => \$_edit,
40                 'rmdir' => \$_rmdir,
41                 'help|H|h' => \$_help,
42                 'find-copies-harder' => \$_find_copies_harder,
43                 'l=i' => \$_l,
44                 'no-stop-on-copy' => \$_no_stop_copy );
45 my %cmd = (
46         fetch => [ \&fetch, "Download new revisions from SVN" ],
47         init => [ \&init, "Initialize and fetch (import)"],
48         commit => [ \&commit, "Commit git revisions to SVN" ],
49         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)" ],
50         help => [ \&usage, "Show help" ],
51 );
52 my $cmd;
53 for (my $i = 0; $i < @ARGV; $i++) {
54         if (defined $cmd{$ARGV[$i]}) {
55                 $cmd = $ARGV[$i];
56                 splice @ARGV, $i, 1;
57                 last;
58         }
59 };
60
61 # we may be called as git-svn-(command), or git-svn(command).
62 foreach (keys %cmd) {
63         if (/git\-svn\-?($_)(?:\.\w+)?$/) {
64                 $cmd = $1;
65                 last;
66         }
67 }
68 usage(0) if $_help;
69 usage(1) unless (defined $cmd);
70 svn_check_ignore_externals();
71 $cmd{$cmd}->[0]->(@ARGV);
72 exit 0;
73
74 ####################### primary functions ######################
75 sub usage {
76         my $exit = shift || 0;
77         my $fd = $exit ? \*STDERR : \*STDOUT;
78         print $fd <<"";
79 git-svn - bidirectional operations between a single Subversion tree and git
80 Usage: $0 <command> [options] [arguments]\n
81 Available commands:
82
83         foreach (sort keys %cmd) {
84                 print $fd '  ',pack('A10',$_),$cmd{$_}->[1],"\n";
85         }
86         print $fd <<"";
87 \nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
88 you're tracking multiple SVN branches/repositories in one git repository
89 and want to keep them separate.
90
91         exit $exit;
92 }
93
94 sub rebuild {
95         $SVN_URL = shift or undef;
96         my $repo_uuid;
97         my $newest_rev = 0;
98
99         my $pid = open(my $rev_list,'-|');
100         defined $pid or croak $!;
101         if ($pid == 0) {
102                 exec("git-rev-list","$GIT_SVN-HEAD") or croak $!;
103         }
104         my $first;
105         while (<$rev_list>) {
106                 chomp;
107                 my $c = $_;
108                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
109                 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
110                 next if (!@commit); # skip merges
111                 my $id = $commit[$#commit];
112                 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
113                                                 \s([a-f\d\-]+)$/x);
114                 if (!$rev || !$uuid || !$url) {
115                         # some of the original repositories I made had
116                         # indentifiers like this:
117                         ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
118                                                         \@([a-f\d\-]+)/x);
119                         if (!$rev || !$uuid) {
120                                 croak "Unable to extract revision or UUID from ",
121                                         "$c, $id\n";
122                         }
123                 }
124                 print "r$rev = $c\n";
125                 unless (defined $first) {
126                         if (!$SVN_URL && !$url) {
127                                 croak "SVN repository location required: $url\n";
128                         }
129                         $SVN_URL ||= $url;
130                         $repo_uuid = setup_git_svn();
131                         $first = $rev;
132                 }
133                 if ($uuid ne $repo_uuid) {
134                         croak "Repository UUIDs do not match!\ngot: $uuid\n",
135                                                 "expected: $repo_uuid\n";
136                 }
137                 assert_revision_eq_or_unknown($rev, $c);
138                 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
139                 $newest_rev = $rev if ($rev > $newest_rev);
140         }
141         close $rev_list or croak $?;
142         if (!chdir $SVN_WC) {
143                 my @svn_co = ('svn','co',"-r$first");
144                 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
145                 sys(@svn_co, $SVN_URL, $SVN_WC);
146                 chdir $SVN_WC or croak $!;
147         }
148
149         $pid = fork;
150         defined $pid or croak $!;
151         if ($pid == 0) {
152                 my @svn_up = qw(svn up);
153                 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
154                 sys(@svn_up,"-r$newest_rev");
155                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
156                 git_addremove();
157                 exec('git-write-tree');
158         }
159         waitpid $pid, 0;
160 }
161
162 sub init {
163         $SVN_URL = shift or croak "SVN repository location required\n";
164         unless (-d $GIT_DIR) {
165                 sys('git-init-db');
166         }
167         setup_git_svn();
168 }
169
170 sub fetch {
171         my (@parents) = @_;
172         $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
173         my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
174         unless ($_revision) {
175                 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
176         }
177         push @log_args, "-r$_revision";
178         push @log_args, '--stop-on-copy' unless $_no_stop_copy;
179
180         my $svn_log = svn_log_raw(@log_args);
181         @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
182
183         my $base = shift @$svn_log or croak "No base revision!\n";
184         my $last_commit = undef;
185         unless (-d $SVN_WC) {
186                 my @svn_co = ('svn','co',"-r$base->{revision}");
187                 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
188                 sys(@svn_co, $SVN_URL, $SVN_WC);
189                 chdir $SVN_WC or croak $!;
190                 $last_commit = git_commit($base, @parents);
191                 unless (-f "$GIT_DIR/refs/heads/master") {
192                         sys(qw(git-update-ref refs/heads/master),$last_commit);
193                 }
194                 assert_svn_wc_clean($base->{revision}, $last_commit);
195         } else {
196                 chdir $SVN_WC or croak $!;
197                 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
198         }
199         my @svn_up = qw(svn up);
200         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
201         my $last_rev = $base->{revision};
202         foreach my $log_msg (@$svn_log) {
203                 assert_svn_wc_clean($last_rev, $last_commit);
204                 $last_rev = $log_msg->{revision};
205                 sys(@svn_up,"-r$last_rev");
206                 $last_commit = git_commit($log_msg, $last_commit, @parents);
207         }
208         assert_svn_wc_clean($last_rev, $last_commit);
209         return pop @$svn_log;
210 }
211
212 sub commit {
213         my (@commits) = @_;
214         if ($_stdin || !@commits) {
215                 print "Reading from stdin...\n";
216                 @commits = ();
217                 while (<STDIN>) {
218                         if (/\b([a-f\d]{6,40})\b/) {
219                                 unshift @commits, $1;
220                         }
221                 }
222         }
223         my @revs;
224         foreach my $c (@commits) {
225                 chomp(my @tmp = safe_qx('git-rev-parse',$c));
226                 if (scalar @tmp == 1) {
227                         push @revs, $tmp[0];
228                 } elsif (scalar @tmp > 1) {
229                         push @revs, reverse (safe_qx('git-rev-list',@tmp));
230                 } else {
231                         die "Failed to rev-parse $c\n";
232                 }
233         }
234         chomp @revs;
235
236         fetch();
237         chdir $SVN_WC or croak $!;
238         my $svn_current_rev =  svn_info('.')->{'Last Changed Rev'};
239         foreach my $c (@revs) {
240                 print "Committing $c\n";
241                 my $mods = svn_checkout_tree($svn_current_rev, $c);
242                 if (scalar @$mods == 0) {
243                         print "Skipping, no changes detected\n";
244                         next;
245                 }
246                 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
247         }
248         print "Done committing ",scalar @revs," revisions to SVN\n";
249
250 }
251
252 ########################### utility functions #########################
253
254 sub setup_git_svn {
255         defined $SVN_URL or croak "SVN repository location required\n";
256         unless (-d $GIT_DIR) {
257                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
258         }
259         mkpath(["$GIT_DIR/$GIT_SVN"]);
260         mkpath(["$GIT_DIR/$GIT_SVN/info"]);
261         mkpath([$REV_DIR]);
262         s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
263         my $uuid = svn_info($SVN_URL)->{'Repository UUID'} or
264                                         croak "Repository UUID unreadable\n";
265         s_to_file($uuid,"$GIT_DIR/$GIT_SVN/info/uuid");
266
267         open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
268         print $fd '.svn',"\n";
269         close $fd or croak $!;
270         return $uuid;
271 }
272
273 sub assert_svn_wc_clean {
274         my ($svn_rev, $treeish) = @_;
275         croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
276         croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
277         my $svn_info = svn_info('.');
278         if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
279                 croak "Expected r$svn_rev, got r",
280                                 $svn_info->{'Last Changed Rev'},"\n";
281         }
282         my @status = grep(!/^Performing status on external/,(`svn status`));
283         @status = grep(!/^\s*$/,@status);
284         if (scalar @status) {
285                 print STDERR "Tree ($SVN_WC) is not clean:\n";
286                 print STDERR $_ foreach @status;
287                 croak;
288         }
289         assert_tree($treeish);
290 }
291
292 sub assert_tree {
293         my ($treeish) = @_;
294         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
295         chomp(my $type = `git-cat-file -t $treeish`);
296         my $expected;
297         while ($type eq 'tag') {
298                 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
299         }
300         if ($type eq 'commit') {
301                 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
302                 ($expected) = ($expected =~ /^tree ($sha1)$/);
303                 die "Unable to get tree from $treeish\n" unless $expected;
304         } elsif ($type eq 'tree') {
305                 $expected = $treeish;
306         } else {
307                 die "$treeish is a $type, expected tree, tag or commit\n";
308         }
309
310         my $old_index = $ENV{GIT_INDEX_FILE};
311         my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
312         if (-e $tmpindex) {
313                 unlink $tmpindex or croak $!;
314         }
315         $ENV{GIT_INDEX_FILE} = $tmpindex;
316         git_addremove();
317         chomp(my $tree = `git-write-tree`);
318         if ($old_index) {
319                 $ENV{GIT_INDEX_FILE} = $old_index;
320         } else {
321                 delete $ENV{GIT_INDEX_FILE};
322         }
323         if ($tree ne $expected) {
324                 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
325         }
326 }
327
328 sub parse_diff_tree {
329         my $diff_fh = shift;
330         local $/ = "\0";
331         my $state = 'meta';
332         my @mods;
333         while (<$diff_fh>) {
334                 chomp $_; # this gets rid of the trailing "\0"
335                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
336                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
337                         push @mods, {   mode_a => $1, mode_b => $2,
338                                         sha1_b => $3, chg => $4 };
339                         if ($4 =~ /^(?:C|R)$/) {
340                                 $state = 'file_a';
341                         } else {
342                                 $state = 'file_b';
343                         }
344                 } elsif ($state eq 'file_a') {
345                         my $x = $mods[$#mods] or croak "Empty array\n";
346                         if ($x->{chg} !~ /^(?:C|R)$/) {
347                                 croak "Error parsing $_, $x->{chg}\n";
348                         }
349                         $x->{file_a} = $_;
350                         $state = 'file_b';
351                 } elsif ($state eq 'file_b') {
352                         my $x = $mods[$#mods] or croak "Empty array\n";
353                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
354                                 croak "Error parsing $_, $x->{chg}\n";
355                         }
356                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
357                                 croak "Error parsing $_, $x->{chg}\n";
358                         }
359                         $x->{file_b} = $_;
360                         $state = 'meta';
361                 } else {
362                         croak "Error parsing $_\n";
363                 }
364         }
365         close $diff_fh or croak $!;
366
367         return \@mods;
368 }
369
370 sub svn_check_prop_executable {
371         my $m = shift;
372         return if -l $m->{file_b};
373         if ($m->{mode_b} =~ /755$/) {
374                 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
375                 if ($m->{mode_a} !~ /755$/) {
376                         sys(qw(svn propset svn:executable 1), $m->{file_b});
377                 }
378                 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
379         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
380                 sys(qw(svn propdel svn:executable), $m->{file_b});
381                 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
382                 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
383         }
384 }
385
386 sub svn_ensure_parent_path {
387         my $dir_b = dirname(shift);
388         svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
389         mkpath([$dir_b]) unless (-d $dir_b);
390         sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
391 }
392
393 sub precommit_check {
394         my $mods = shift;
395         my (%rm_file, %rmdir_check, %added_check);
396
397         my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
398         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
399                 if ($m->{chg} eq 'R') {
400                         if (-d $m->{file_b}) {
401                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
402                         }
403                         # dir/$file => dir/file/$file
404                         my $dirname = dirname($m->{file_b});
405                         while ($dirname ne File::Spec->curdir) {
406                                 if ($dirname ne $m->{file_a}) {
407                                         $dirname = dirname($dirname);
408                                         next;
409                                 }
410                                 err_file_to_dir("$m->{file_a} => $m->{file_b}");
411                         }
412                         # baz/zzz => baz (baz is a file)
413                         $dirname = dirname($m->{file_a});
414                         while ($dirname ne File::Spec->curdir) {
415                                 if ($dirname ne $m->{file_b}) {
416                                         $dirname = dirname($dirname);
417                                         next;
418                                 }
419                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
420                         }
421                 }
422                 if ($m->{chg} =~ /^(D|R)$/) {
423                         my $t = $1 eq 'D' ? 'file_b' : 'file_a';
424                         $rm_file{ $m->{$t} } = 1;
425                         my $dirname = dirname( $m->{$t} );
426                         my $basename = basename( $m->{$t} );
427                         $rmdir_check{$dirname}->{$basename} = 1;
428                 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
429                         if (-d $m->{file_b}) {
430                                 err_dir_to_file($m->{file_b});
431                         }
432                         my $dirname = dirname( $m->{file_b} );
433                         my $basename = basename( $m->{file_b} );
434                         $added_check{$dirname}->{$basename} = 1;
435                         while ($dirname ne File::Spec->curdir) {
436                                 if ($rm_file{$dirname}) {
437                                         err_file_to_dir($m->{file_b});
438                                 }
439                                 $dirname = dirname $dirname;
440                         }
441                 }
442         }
443         return (\%rmdir_check, \%added_check);
444
445         sub err_dir_to_file {
446                 my $file = shift;
447                 print STDERR "Node change from directory to file ",
448                                 "is not supported by Subversion: ",$file,"\n";
449                 exit 1;
450         }
451         sub err_file_to_dir {
452                 my $file = shift;
453                 print STDERR "Node change from file to directory ",
454                                 "is not supported by Subversion: ",$file,"\n";
455                 exit 1;
456         }
457 }
458
459 sub svn_checkout_tree {
460         my ($svn_rev, $treeish) = @_;
461         my $from = file_to_s("$REV_DIR/$svn_rev");
462         assert_svn_wc_clean($svn_rev,$from);
463         print "diff-tree '$from' '$treeish'\n";
464         my $pid = open my $diff_fh, '-|';
465         defined $pid or croak $!;
466         if ($pid == 0) {
467                 my @diff_tree = qw(git-diff-tree -z -r -C);
468                 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
469                 push @diff_tree, "-l$_l" if defined $_l;
470                 exec(@diff_tree, $from, $treeish) or croak $!;
471         }
472         my $mods = parse_diff_tree($diff_fh);
473         unless (@$mods) {
474                 # git can do empty commits, SVN doesn't allow it...
475                 return $mods;
476         }
477         my ($rm, $add) = precommit_check($mods);
478
479         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
480         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
481                 if ($m->{chg} eq 'C') {
482                         svn_ensure_parent_path( $m->{file_b} );
483                         sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
484                         apply_mod_line_blob($m);
485                         svn_check_prop_executable($m);
486                 } elsif ($m->{chg} eq 'D') {
487                         sys(qw(svn rm --force), $m->{file_b});
488                 } elsif ($m->{chg} eq 'R') {
489                         svn_ensure_parent_path( $m->{file_b} );
490                         sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
491                         apply_mod_line_blob($m);
492                         svn_check_prop_executable($m);
493                 } elsif ($m->{chg} eq 'M') {
494                         apply_mod_line_blob($m);
495                         svn_check_prop_executable($m);
496                 } elsif ($m->{chg} eq 'T') {
497                         sys(qw(svn rm --force),$m->{file_b});
498                         apply_mod_line_blob($m);
499                         sys(qw(svn add --force), $m->{file_b});
500                         svn_check_prop_executable($m);
501                 } elsif ($m->{chg} eq 'A') {
502                         svn_ensure_parent_path( $m->{file_b} );
503                         apply_mod_line_blob($m);
504                         sys(qw(svn add --force), $m->{file_b});
505                         svn_check_prop_executable($m);
506                 } else {
507                         croak "Invalid chg: $m->{chg}\n";
508                 }
509         }
510
511         assert_tree($treeish);
512         if ($_rmdir) { # remove empty directories
513                 handle_rmdir($rm, $add);
514         }
515         assert_tree($treeish);
516         return $mods;
517 }
518
519 # svn ls doesn't work with respect to the current working tree, but what's
520 # in the repository.  There's not even an option for it... *sigh*
521 # (added files don't show up and removed files remain in the ls listing)
522 sub svn_ls_current {
523         my ($dir, $rm, $add) = @_;
524         chomp(my @ls = safe_qx('svn','ls',$dir));
525         my @ret = ();
526         foreach (@ls) {
527                 s#/$##; # trailing slashes are evil
528                 push @ret, $_ unless $rm->{$dir}->{$_};
529         }
530         if (exists $add->{$dir}) {
531                 push @ret, keys %{$add->{$dir}};
532         }
533         return \@ret;
534 }
535
536 sub handle_rmdir {
537         my ($rm, $add) = @_;
538
539         foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
540                 my $ls = svn_ls_current($dir, $rm, $add);
541                 next if (scalar @$ls);
542                 sys(qw(svn rm --force),$dir);
543
544                 my $dn = dirname $dir;
545                 $rm->{ $dn }->{ basename $dir } = 1;
546                 $ls = svn_ls_current($dn, $rm, $add);
547                 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
548                         sys(qw(svn rm --force),$dn);
549                         $dir = basename $dn;
550                         $dn = dirname $dn;
551                         $rm->{ $dn }->{ $dir } = 1;
552                         $ls = svn_ls_current($dn, $rm, $add);
553                 }
554         }
555 }
556
557 sub svn_commit_tree {
558         my ($svn_rev, $commit) = @_;
559         my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
560         open my $msg, '>', $commit_msg  or croak $!;
561
562         chomp(my $type = `git-cat-file -t $commit`);
563         if ($type eq 'commit') {
564                 my $pid = open my $msg_fh, '-|';
565                 defined $pid or croak $!;
566
567                 if ($pid == 0) {
568                         exec(qw(git-cat-file commit), $commit) or croak $!;
569                 }
570                 my $in_msg = 0;
571                 while (<$msg_fh>) {
572                         if (!$in_msg) {
573                                 $in_msg = 1 if (/^\s*$/);
574                         } else {
575                                 print $msg $_ or croak $!;
576                         }
577                 }
578                 close $msg_fh or croak $!;
579         }
580         close $msg or croak $!;
581
582         if ($_edit || ($type eq 'tree')) {
583                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
584                 system($editor, $commit_msg);
585         }
586         my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
587         my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
588         unlink $commit_msg;
589         defined $committed or croak
590                         "Commit output failed to parse committed revision!\n",
591                         join("\n",@ci_output),"\n";
592         my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
593
594         # resync immediately
595         my @svn_up = (qw(svn up), "-r$svn_rev");
596         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
597         sys(@svn_up);
598         return fetch("$rev_committed=$commit")->{revision};
599 }
600
601 sub svn_log_raw {
602         my (@log_args) = @_;
603         my $pid = open my $log_fh,'-|';
604         defined $pid or croak $!;
605
606         if ($pid == 0) {
607                 exec (qw(svn log), @log_args) or croak $!
608         }
609
610         my @svn_log;
611         my $state = 'sep';
612         while (<$log_fh>) {
613                 chomp;
614                 if (/^\-{72}$/) {
615                         if ($state eq 'msg') {
616                                 if ($svn_log[$#svn_log]->{lines}) {
617                                         $svn_log[$#svn_log]->{msg} .= $_."\n";
618                                         unless(--$svn_log[$#svn_log]->{lines}) {
619                                                 $state = 'sep';
620                                         }
621                                 } else {
622                                         croak "Log parse error at: $_\n",
623                                                 $svn_log[$#svn_log]->{revision},
624                                                 "\n";
625                                 }
626                                 next;
627                         }
628                         if ($state ne 'sep') {
629                                 croak "Log parse error at: $_\n",
630                                         "state: $state\n",
631                                         $svn_log[$#svn_log]->{revision},
632                                         "\n";
633                         }
634                         $state = 'rev';
635
636                         # if we have an empty log message, put something there:
637                         if (@svn_log) {
638                                 $svn_log[$#svn_log]->{msg} ||= "\n";
639                                 delete $svn_log[$#svn_log]->{lines};
640                         }
641                         next;
642                 }
643                 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
644                         my $rev = $1;
645                         my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
646                         ($lines) = ($lines =~ /(\d+)/);
647                         my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
648                                         /(\d{4})\-(\d\d)\-(\d\d)\s
649                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
650                                          or croak "Failed to parse date: $date\n";
651                         my %log_msg = ( revision => $rev,
652                                         date => "$tz $Y-$m-$d $H:$M:$S",
653                                         author => $author,
654                                         lines => $lines,
655                                         msg => '' );
656                         push @svn_log, \%log_msg;
657                         $state = 'msg_start';
658                         next;
659                 }
660                 # skip the first blank line of the message:
661                 if ($state eq 'msg_start' && /^$/) {
662                         $state = 'msg';
663                 } elsif ($state eq 'msg') {
664                         if ($svn_log[$#svn_log]->{lines}) {
665                                 $svn_log[$#svn_log]->{msg} .= $_."\n";
666                                 unless (--$svn_log[$#svn_log]->{lines}) {
667                                         $state = 'sep';
668                                 }
669                         } else {
670                                 croak "Log parse error at: $_\n",
671                                         $svn_log[$#svn_log]->{revision},"\n";
672                         }
673                 }
674         }
675         close $log_fh or croak $?;
676         return \@svn_log;
677 }
678
679 sub svn_info {
680         my $url = shift || $SVN_URL;
681
682         my $pid = open my $info_fh, '-|';
683         defined $pid or croak $!;
684
685         if ($pid == 0) {
686                 exec(qw(svn info),$url) or croak $!;
687         }
688
689         my $ret = {};
690         # only single-lines seem to exist in svn info output
691         while (<$info_fh>) {
692                 chomp $_;
693                 if (m#^([^:]+)\s*:\s*(\S*)$#) {
694                         $ret->{$1} = $2;
695                         push @{$ret->{-order}}, $1;
696                 }
697         }
698         close $info_fh or croak $!;
699         return $ret;
700 }
701
702 sub sys { system(@_) == 0 or croak $? }
703
704 sub git_addremove {
705         system( "git-diff-files --name-only -z ".
706                                 " | git-update-index --remove -z --stdin && ".
707                 "git-ls-files -z --others ".
708                         "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
709                                 " | git-update-index --add -z --stdin"
710                 ) == 0 or croak $?
711 }
712
713 sub s_to_file {
714         my ($str, $file, $mode) = @_;
715         open my $fd,'>',$file or croak $!;
716         print $fd $str,"\n" or croak $!;
717         close $fd or croak $!;
718         chmod ($mode &~ umask, $file) if (defined $mode);
719 }
720
721 sub file_to_s {
722         my $file = shift;
723         open my $fd,'<',$file or croak "$!: file: $file\n";
724         local $/;
725         my $ret = <$fd>;
726         close $fd or croak $!;
727         $ret =~ s/\s*$//s;
728         return $ret;
729 }
730
731 sub assert_revision_unknown {
732         my $revno = shift;
733         if (-f "$REV_DIR/$revno") {
734                 croak "$REV_DIR/$revno already exists! ",
735                                 "Why are we refetching it?";
736         }
737 }
738
739 sub assert_revision_eq_or_unknown {
740         my ($revno, $commit) = @_;
741         if (-f "$REV_DIR/$revno") {
742                 my $current = file_to_s("$REV_DIR/$revno");
743                 if ($commit ne $current) {
744                         croak "$REV_DIR/$revno already exists!\n",
745                                 "current: $current\nexpected: $commit\n";
746                 }
747                 return;
748         }
749 }
750
751 sub git_commit {
752         my ($log_msg, @parents) = @_;
753         assert_revision_unknown($log_msg->{revision});
754         my $out_fh = IO::File->new_tmpfile or croak $!;
755         my $info = svn_info('.');
756         my $uuid = $info->{'Repository UUID'};
757         defined $uuid or croak "Unable to get Repository UUID\n";
758
759         # commit parents can be conditionally bound to a particular
760         # svn revision via: "svn_revno=commit_sha1", filter them out here:
761         my @exec_parents;
762         foreach my $p (@parents) {
763                 next unless defined $p;
764                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
765                         if ($1 == $log_msg->{revision}) {
766                                 push @exec_parents, $2;
767                         }
768                 } else {
769                         push @exec_parents, $p if $p =~ /$sha1_short/o;
770                 }
771         }
772
773         my $pid = fork;
774         defined $pid or croak $!;
775         if ($pid == 0) {
776                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
777                 git_addremove();
778                 chomp(my $tree = `git-write-tree`);
779                 croak if $?;
780                 my $msg_fh = IO::File->new_tmpfile or croak $!;
781                 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
782                                         "$SVN_URL\@$log_msg->{revision}",
783                                         " $uuid\n" or croak $!;
784                 $msg_fh->flush == 0 or croak $!;
785                 seek $msg_fh, 0, 0 or croak $!;
786
787                 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} =
788                                                 $log_msg->{author};
789                 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
790                                                 $log_msg->{author}."\@$uuid";
791                 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} =
792                                                 $log_msg->{date};
793                 my @exec = ('git-commit-tree',$tree);
794                 push @exec, '-p', $_  foreach @exec_parents;
795                 open STDIN, '<&', $msg_fh or croak $!;
796                 open STDOUT, '>&', $out_fh or croak $!;
797                 exec @exec or croak $!;
798         }
799         waitpid($pid,0);
800         croak if $?;
801
802         $out_fh->flush == 0 or croak $!;
803         seek $out_fh, 0, 0 or croak $!;
804         chomp(my $commit = do { local $/; <$out_fh> });
805         if ($commit !~ /^$sha1$/o) {
806                 croak "Failed to commit, invalid sha1: $commit\n";
807         }
808         my @update_ref = ('git-update-ref',"refs/heads/$GIT_SVN-HEAD",$commit);
809         if (my $primary_parent = shift @exec_parents) {
810                 push @update_ref, $primary_parent;
811         }
812         sys(@update_ref);
813         sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
814         print "r$log_msg->{revision} = $commit\n";
815         return $commit;
816 }
817
818 sub apply_mod_line_blob {
819         my $m = shift;
820         if ($m->{mode_b} =~ /^120/) {
821                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
822         } else {
823                 blob_to_file($m->{sha1_b}, $m->{file_b});
824         }
825 }
826
827 sub blob_to_symlink {
828         my ($blob, $link) = @_;
829         defined $link or croak "\$link not defined!\n";
830         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
831         if (-l $link || -f _) {
832                 unlink $link or croak $!;
833         }
834
835         my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
836         symlink $dest, $link or croak $!;
837 }
838
839 sub blob_to_file {
840         my ($blob, $file) = @_;
841         defined $file or croak "\$file not defined!\n";
842         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
843         if (-l $file || -f _) {
844                 unlink $file or croak $!;
845         }
846
847         open my $blob_fh, '>', $file or croak "$!: $file\n";
848         my $pid = fork;
849         defined $pid or croak $!;
850
851         if ($pid == 0) {
852                 open STDOUT, '>&', $blob_fh or croak $!;
853                 exec('git-cat-file','blob',$blob);
854         }
855         waitpid $pid, 0;
856         croak $? if $?;
857
858         close $blob_fh or croak $!;
859 }
860
861 sub safe_qx {
862         my $pid = open my $child, '-|';
863         defined $pid or croak $!;
864         if ($pid == 0) {
865                 exec(@_) or croak $?;
866         }
867         my @ret = (<$child>);
868         close $child or croak $?;
869         die $? if $?; # just in case close didn't error out
870         return wantarray ? @ret : join('',@ret);
871 }
872
873 sub svn_check_ignore_externals {
874         return if $_no_ignore_ext;
875         unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
876                 print STDERR "W: Installed svn version does not support ",
877                                 "--ignore-externals\n";
878                 $_no_ignore_ext = 1;
879         }
880 }
881 __END__
882
883 Data structures:
884
885 @svn_log = array of log_msg hashes
886
887 $log_msg hash
888 {
889         msg => 'whitespace-formatted log entry
890 ',                                              # trailing newline is preserved
891         revision => '8',                        # integer
892         date => '2004-02-24T17:01:44.108345Z',  # commit date
893         author => 'committer name'
894 };
895
896
897 @mods = array of diff-index line hashes, each element represents one line
898         of diff-index output
899
900 diff-index line ($m hash)
901 {
902         mode_a => first column of diff-index output, no leading ':',
903         mode_b => second column of diff-index output,
904         sha1_b => sha1sum of the final blob,
905         chg => change type [MCRAD],
906         file_a => original file name of a file (iff chg is 'C' or 'R')
907         file_b => new/current file name of a file (any chg)
908 }
909 ;