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