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