git-svn: remove any need for the XML::Simple dependency
[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                 svn_checkout_tree($svn_current_rev, $c);
242                 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
243         }
244         print "Done committing ",scalar @revs," revisions to SVN\n";
245
246 }
247
248 ########################### utility functions #########################
249
250 sub setup_git_svn {
251         defined $SVN_URL or croak "SVN repository location required\n";
252         unless (-d $GIT_DIR) {
253                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
254         }
255         mkpath(["$GIT_DIR/$GIT_SVN"]);
256         mkpath(["$GIT_DIR/$GIT_SVN/info"]);
257         mkpath([$REV_DIR]);
258         s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
259         my $uuid = svn_info($SVN_URL)->{'Repository UUID'} or
260                                         croak "Repository UUID unreadable\n";
261         s_to_file($uuid,"$GIT_DIR/$GIT_SVN/info/uuid");
262
263         open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
264         print $fd '.svn',"\n";
265         close $fd or croak $!;
266         return $uuid;
267 }
268
269 sub assert_svn_wc_clean {
270         my ($svn_rev, $commit) = @_;
271         croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
272         croak "$commit is not a sha1!\n" unless ($commit =~ /^$sha1$/o);
273         my $svn_info = svn_info('.');
274         if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
275                 croak "Expected r$svn_rev, got r",
276                                 $svn_info->{'Last Changed Rev'},"\n";
277         }
278         my @status = grep(!/^Performing status on external/,(`svn status`));
279         @status = grep(!/^\s*$/,@status);
280         if (scalar @status) {
281                 print STDERR "Tree ($SVN_WC) is not clean:\n";
282                 print STDERR $_ foreach @status;
283                 croak;
284         }
285         my ($tree_a) = grep(/^tree $sha1$/o,`git-cat-file commit $commit`);
286         $tree_a =~ s/^tree //;
287         chomp $tree_a;
288         chomp(my $tree_b = `GIT_INDEX_FILE=$GIT_SVN_INDEX git-write-tree`);
289         if ($tree_a ne $tree_b) {
290                 croak "$svn_rev != $commit, $tree_a != $tree_b\n";
291         }
292 }
293
294 sub parse_diff_tree {
295         my $diff_fh = shift;
296         local $/ = "\0";
297         my $state = 'meta';
298         my @mods;
299         while (<$diff_fh>) {
300                 chomp $_; # this gets rid of the trailing "\0"
301                 print $_,"\n";
302                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
303                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
304                         push @mods, {   mode_a => $1, mode_b => $2,
305                                         sha1_b => $3, chg => $4 };
306                         if ($4 =~ /^(?:C|R)$/) {
307                                 $state = 'file_a';
308                         } else {
309                                 $state = 'file_b';
310                         }
311                 } elsif ($state eq 'file_a') {
312                         my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
313                         if ($x->{chg} !~ /^(?:C|R)$/) {
314                                 croak __LINE__,": Error parsing $_, $x->{chg}\n";
315                         }
316                         $x->{file_a} = $_;
317                         $state = 'file_b';
318                 } elsif ($state eq 'file_b') {
319                         my $x = $mods[$#mods] or croak __LINE__,": Empty array\n";
320                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
321                                 croak __LINE__,": Error parsing $_, $x->{chg}\n";
322                         }
323                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
324                                 croak __LINE__,": Error parsing $_, $x->{chg}\n";
325                         }
326                         $x->{file_b} = $_;
327                         $state = 'meta';
328                 } else {
329                         croak __LINE__,": Error parsing $_\n";
330                 }
331         }
332         close $diff_fh or croak $!;
333         return \@mods;
334 }
335
336 sub svn_check_prop_executable {
337         my $m = shift;
338         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
339                 sys(qw(svn propset svn:executable 1), $m->{file_b});
340         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
341                 sys(qw(svn propdel svn:executable), $m->{file_b});
342         }
343 }
344
345 sub svn_ensure_parent_path {
346         my $dir_b = dirname(shift);
347         svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
348         mkpath([$dir_b]) unless (-d $dir_b);
349         sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
350 }
351
352 sub svn_checkout_tree {
353         my ($svn_rev, $commit) = @_;
354         my $from = file_to_s("$REV_DIR/$svn_rev");
355         assert_svn_wc_clean($svn_rev,$from);
356         print "diff-tree '$from' '$commit'\n";
357         my $pid = open my $diff_fh, '-|';
358         defined $pid or croak $!;
359         if ($pid == 0) {
360                 my @diff_tree = qw(git-diff-tree -z -r -C);
361                 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
362                 push @diff_tree, "-l$_l" if defined $_l;
363                 exec(@diff_tree, $from, $commit) or croak $!;
364         }
365         my $mods = parse_diff_tree($diff_fh);
366         unless (@$mods) {
367                 # git can do empty commits, SVN doesn't allow it...
368                 return $svn_rev;
369         }
370         my %rm;
371         foreach my $m (@$mods) {
372                 if ($m->{chg} eq 'C') {
373                         svn_ensure_parent_path( $m->{file_b} );
374                         sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
375                         blob_to_file(           $m->{sha1_b}, $m->{file_b});
376                         svn_check_prop_executable($m);
377                 } elsif ($m->{chg} eq 'D') {
378                         $rm{dirname $m->{file_b}}->{basename $m->{file_b}} = 1;
379                         sys(qw(svn rm --force), $m->{file_b});
380                 } elsif ($m->{chg} eq 'R') {
381                         svn_ensure_parent_path( $m->{file_b} );
382                         sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
383                         blob_to_file(           $m->{sha1_b}, $m->{file_b});
384                         svn_check_prop_executable($m);
385                         $rm{dirname $m->{file_a}}->{basename $m->{file_a}} = 1;
386                 } elsif ($m->{chg} eq 'M') {
387                         if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^120/) {
388                                 unlink $m->{file_b} or croak $!;
389                                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
390                         } else {
391                                 blob_to_file($m->{sha1_b}, $m->{file_b});
392                         }
393                         svn_check_prop_executable($m);
394                 } elsif ($m->{chg} eq 'T') {
395                         sys(qw(svn rm --force),$m->{file_b});
396                         if ($m->{mode_b} =~ /^120/ && $m->{mode_a} =~ /^100/) {
397                                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
398                         } else {
399                                 blob_to_file($m->{sha1_b}, $m->{file_b});
400                         }
401                         svn_check_prop_executable($m);
402                         sys(qw(svn add --force), $m->{file_b});
403                 } elsif ($m->{chg} eq 'A') {
404                         svn_ensure_parent_path( $m->{file_b} );
405                         blob_to_file(           $m->{sha1_b}, $m->{file_b});
406                         if ($m->{mode_b} =~ /755$/) {
407                                 chmod 0755, $m->{file_b};
408                         }
409                         sys(qw(svn add --force), $m->{file_b});
410                 } else {
411                         croak "Invalid chg: $m->{chg}\n";
412                 }
413         }
414         if ($_rmdir) {
415                 my $old_index = $ENV{GIT_INDEX_FILE};
416                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
417                 foreach my $dir (keys %rm) {
418                         my $files = $rm{$dir};
419                         my @files;
420                         foreach (safe_qx('svn','ls',$dir)) {
421                                 chomp;
422                                 push @files, $_ unless $files->{$_};
423                         }
424                         sys(qw(svn rm),$dir) unless @files;
425                 }
426                 if ($old_index) {
427                         $ENV{GIT_INDEX_FILE} = $old_index;
428                 } else {
429                         delete $ENV{GIT_INDEX_FILE};
430                 }
431         }
432 }
433
434 sub svn_commit_tree {
435         my ($svn_rev, $commit) = @_;
436         my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
437         open my $msg, '>', $commit_msg  or croak $!;
438
439         chomp(my $type = `git-cat-file -t $commit`);
440         if ($type eq 'commit') {
441                 my $pid = open my $msg_fh, '-|';
442                 defined $pid or croak $!;
443
444                 if ($pid == 0) {
445                         exec(qw(git-cat-file commit), $commit) or croak $!;
446                 }
447                 my $in_msg = 0;
448                 while (<$msg_fh>) {
449                         if (!$in_msg) {
450                                 $in_msg = 1 if (/^\s*$/);
451                         } else {
452                                 print $msg $_ or croak $!;
453                         }
454                 }
455                 close $msg_fh or croak $!;
456         }
457         close $msg or croak $!;
458
459         if ($_edit || ($type eq 'tree')) {
460                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
461                 system($editor, $commit_msg);
462         }
463         my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
464         my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
465         unlink $commit_msg;
466         defined $committed or croak
467                         "Commit output failed to parse committed revision!\n",
468                         join("\n",@ci_output),"\n";
469         my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
470
471         # resync immediately
472         my @svn_up = (qw(svn up), "-r$svn_rev");
473         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
474         sys(@svn_up);
475         return fetch("$rev_committed=$commit")->{revision};
476 }
477
478 sub svn_log_raw {
479         my (@log_args) = @_;
480         my $pid = open my $log_fh,'-|';
481         defined $pid or croak $!;
482
483         if ($pid == 0) {
484                 exec (qw(svn log), @log_args) or croak $!
485         }
486
487         my @svn_log;
488         my $state = 'sep';
489         while (<$log_fh>) {
490                 chomp;
491                 if (/^\-{72}$/) {
492                         if ($state eq 'msg') {
493                                 if ($svn_log[$#svn_log]->{lines}) {
494                                         $svn_log[$#svn_log]->{msg} .= $_."\n";
495                                         unless(--$svn_log[$#svn_log]->{lines}) {
496                                                 $state = 'sep';
497                                         }
498                                 } else {
499                                         croak "Log parse error at: $_\n",
500                                                 $svn_log[$#svn_log]->{revision},
501                                                 "\n";
502                                 }
503                                 next;
504                         }
505                         if ($state ne 'sep') {
506                                 croak "Log parse error at: $_\n",
507                                         "state: $state\n",
508                                         $svn_log[$#svn_log]->{revision},
509                                         "\n";
510                         }
511                         $state = 'rev';
512
513                         # if we have an empty log message, put something there:
514                         if (@svn_log) {
515                                 $svn_log[$#svn_log]->{msg} ||= "\n";
516                                 delete $svn_log[$#svn_log]->{lines};
517                         }
518                         next;
519                 }
520                 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
521                         my $rev = $1;
522                         my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
523                         ($lines) = ($lines =~ /(\d+)/);
524                         my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
525                                         /(\d{4})\-(\d\d)\-(\d\d)\s
526                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
527                                          or croak "Failed to parse date: $date\n";
528                         my %log_msg = ( revision => $rev,
529                                         date => "$tz $Y-$m-$d $H:$M:$S",
530                                         author => $author,
531                                         lines => $lines,
532                                         msg => '' );
533                         push @svn_log, \%log_msg;
534                         $state = 'msg_start';
535                         next;
536                 }
537                 # skip the first blank line of the message:
538                 if ($state eq 'msg_start' && /^$/) {
539                         $state = 'msg';
540                 } elsif ($state eq 'msg') {
541                         if ($svn_log[$#svn_log]->{lines}) {
542                                 $svn_log[$#svn_log]->{msg} .= $_."\n";
543                                 unless (--$svn_log[$#svn_log]->{lines}) {
544                                         $state = 'sep';
545                                 }
546                         } else {
547                                 croak "Log parse error at: $_\n",
548                                         $svn_log[$#svn_log]->{revision},"\n";
549                         }
550                 }
551         }
552         close $log_fh or croak $?;
553         return \@svn_log;
554 }
555
556 sub svn_info {
557         my $url = shift || $SVN_URL;
558
559         my $pid = open my $info_fh, '-|';
560         defined $pid or croak $!;
561
562         if ($pid == 0) {
563                 exec(qw(svn info),$url) or croak $!;
564         }
565
566         my $ret = {};
567         # only single-lines seem to exist in svn info output
568         while (<$info_fh>) {
569                 chomp $_;
570                 if (m#^([^:]+)\s*:\s*(\S*)$#) {
571                         $ret->{$1} = $2;
572                         push @{$ret->{-order}}, $1;
573                 }
574         }
575         close $info_fh or croak $!;
576         return $ret;
577 }
578
579 sub sys { system(@_) == 0 or croak $? }
580
581 sub git_addremove {
582         system( "git-diff-files --name-only -z ".
583                                 " | git-update-index --remove -z --stdin; ".
584                 "git-ls-files -z --others ".
585                         "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
586                                 " | git-update-index --add -z --stdin; "
587                 ) == 0 or croak $?
588 }
589
590 sub s_to_file {
591         my ($str, $file, $mode) = @_;
592         open my $fd,'>',$file or croak $!;
593         print $fd $str,"\n" or croak $!;
594         close $fd or croak $!;
595         chmod ($mode &~ umask, $file) if (defined $mode);
596 }
597
598 sub file_to_s {
599         my $file = shift;
600         open my $fd,'<',$file or croak "$!: file: $file\n";
601         local $/;
602         my $ret = <$fd>;
603         close $fd or croak $!;
604         $ret =~ s/\s*$//s;
605         return $ret;
606 }
607
608 sub assert_revision_unknown {
609         my $revno = shift;
610         if (-f "$REV_DIR/$revno") {
611                 croak "$REV_DIR/$revno already exists! ",
612                                 "Why are we refetching it?";
613         }
614 }
615
616 sub assert_revision_eq_or_unknown {
617         my ($revno, $commit) = @_;
618         if (-f "$REV_DIR/$revno") {
619                 my $current = file_to_s("$REV_DIR/$revno");
620                 if ($commit ne $current) {
621                         croak "$REV_DIR/$revno already exists!\n",
622                                 "current: $current\nexpected: $commit\n";
623                 }
624                 return;
625         }
626 }
627
628 sub git_commit {
629         my ($log_msg, @parents) = @_;
630         assert_revision_unknown($log_msg->{revision});
631         my $out_fh = IO::File->new_tmpfile or croak $!;
632         my $info = svn_info('.');
633         my $uuid = $info->{'Repository UUID'};
634         defined $uuid or croak "Unable to get Repository UUID\n";
635
636         # commit parents can be conditionally bound to a particular
637         # svn revision via: "svn_revno=commit_sha1", filter them out here:
638         my @exec_parents;
639         foreach my $p (@parents) {
640                 next unless defined $p;
641                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
642                         if ($1 == $log_msg->{revision}) {
643                                 push @exec_parents, $2;
644                         }
645                 } else {
646                         push @exec_parents, $p if $p =~ /$sha1_short/o;
647                 }
648         }
649
650         my $pid = fork;
651         defined $pid or croak $!;
652         if ($pid == 0) {
653                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
654                 git_addremove();
655                 chomp(my $tree = `git-write-tree`);
656                 croak if $?;
657                 my $msg_fh = IO::File->new_tmpfile or croak $!;
658                 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
659                                         "$SVN_URL\@$log_msg->{revision}",
660                                         " $uuid\n" or croak $!;
661                 $msg_fh->flush == 0 or croak $!;
662                 seek $msg_fh, 0, 0 or croak $!;
663
664                 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} =
665                                                 $log_msg->{author};
666                 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
667                                                 $log_msg->{author}."\@$uuid";
668                 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} =
669                                                 $log_msg->{date};
670                 my @exec = ('git-commit-tree',$tree);
671                 push @exec, '-p', $_  foreach @exec_parents;
672                 open STDIN, '<&', $msg_fh or croak $!;
673                 open STDOUT, '>&', $out_fh or croak $!;
674                 exec @exec or croak $!;
675         }
676         waitpid($pid,0);
677         croak if $?;
678
679         $out_fh->flush == 0 or croak $!;
680         seek $out_fh, 0, 0 or croak $!;
681         chomp(my $commit = do { local $/; <$out_fh> });
682         if ($commit !~ /^$sha1$/o) {
683                 croak "Failed to commit, invalid sha1: $commit\n";
684         }
685         my @update_ref = ('git-update-ref',"refs/heads/$GIT_SVN-HEAD",$commit);
686         if (my $primary_parent = shift @exec_parents) {
687                 push @update_ref, $primary_parent;
688         }
689         sys(@update_ref);
690         sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
691         print "r$log_msg->{revision} = $commit\n";
692         return $commit;
693 }
694
695 sub blob_to_symlink {
696         my ($blob, $link) = @_;
697         defined $link or croak "\$link not defined!\n";
698         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
699         my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
700         symlink $dest, $link or croak $!;
701 }
702
703 sub blob_to_file {
704         my ($blob, $file) = @_;
705         defined $file or croak "\$file not defined!\n";
706         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
707         open my $blob_fh, '>', $file or croak "$!: $file\n";
708         my $pid = fork;
709         defined $pid or croak $!;
710
711         if ($pid == 0) {
712                 open STDOUT, '>&', $blob_fh or croak $!;
713                 exec('git-cat-file','blob',$blob);
714         }
715         waitpid $pid, 0;
716         croak $? if $?;
717
718         close $blob_fh or croak $!;
719 }
720
721 sub safe_qx {
722         my $pid = open my $child, '-|';
723         defined $pid or croak $!;
724         if ($pid == 0) {
725                 exec(@_) or croak $?;
726         }
727         my @ret = (<$child>);
728         close $child or croak $?;
729         die $? if $?; # just in case close didn't error out
730         return wantarray ? @ret : join('',@ret);
731 }
732
733 sub svn_check_ignore_externals {
734         return if $_no_ignore_ext;
735         unless (grep /ignore-externals/,(safe_qx(qw(svn co -h)))) {
736                 print STDERR "W: Installed svn version does not support ",
737                                 "--ignore-externals\n";
738                 $_no_ignore_ext = 1;
739         }
740 }
741 __END__
742
743 Data structures:
744
745 @svn_log = array of log_msg hashes
746
747 $log_msg hash
748 {
749         msg => 'whitespace-formatted log entry
750 ',                                              # trailing newline is preserved
751         revision => '8',                        # integer
752         date => '2004-02-24T17:01:44.108345Z',  # commit date
753         author => 'committer name'
754 };
755
756
757 @mods = array of diff-index line hashes, each element represents one line
758         of diff-index output
759
760 diff-index line ($m hash)
761 {
762         mode_a => first column of diff-index output, no leading ':',
763         mode_b => second column of diff-index output,
764         sha1_b => sha1sum of the final blob,
765         chg => change type [MCRAD],
766         file_a => original file name of a file (iff chg is 'C' or 'R')
767         file_b => new/current file name of a file (any chg)
768 }
769 ;