git-svn: support -C<num> passing to git-diff-tree
[git.git] / contrib / git-svn / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $REV_DIR/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '1.1.0-pre';
12
13 use Cwd qw/abs_path/;
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
16
17 my $LC_ALL = $ENV{LC_ALL};
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 # We don't use any modules not in the standard Perl distribution:
26 use Carp qw/croak/;
27 use IO::File qw//;
28 use File::Basename qw/dirname basename/;
29 use File::Path qw/mkpath/;
30 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
31 use File::Spec qw//;
32 use POSIX qw/strftime/;
33 my $sha1 = qr/[a-f\d]{40}/;
34 my $sha1_short = qr/[a-f\d]{4,40}/;
35 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
36         $_find_copies_harder, $_l, $_cp_similarity,
37         $_version, $_upgrade, $_authors);
38 my (@_branch_from, %tree_map, %users);
39 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
40
41 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
42                 'branch|b=s' => \@_branch_from,
43                 'authors-file|A=s' => \$_authors );
44
45 # yes, 'native' sets "\n".  Patches to fix this for non-*nix systems welcome:
46 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
47
48 my %cmd = (
49         fetch => [ \&fetch, "Download new revisions from SVN",
50                         { 'revision|r=s' => \$_revision, %fc_opts } ],
51         init => [ \&init, "Initialize a repo for tracking" .
52                           " (requires URL argument)", { } ],
53         commit => [ \&commit, "Commit git revisions to SVN",
54                         {       'stdin|' => \$_stdin,
55                                 'edit|e' => \$_edit,
56                                 'rmdir' => \$_rmdir,
57                                 'find-copies-harder' => \$_find_copies_harder,
58                                 'l=i' => \$_l,
59                                 'copy-similarity|C=i'=> \$_cp_similarity,
60                                 %fc_opts,
61                         } ],
62         'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
63         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
64                         { 'no-ignore-externals' => \$_no_ignore_ext,
65                           'upgrade' => \$_upgrade } ],
66 );
67 my $cmd;
68 for (my $i = 0; $i < @ARGV; $i++) {
69         if (defined $cmd{$ARGV[$i]}) {
70                 $cmd = $ARGV[$i];
71                 splice @ARGV, $i, 1;
72                 last;
73         }
74 };
75
76 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
77
78 # convert GetOpt::Long specs for use by git-repo-config
79 foreach my $o (keys %opts) {
80         my $v = $opts{$o};
81         my ($key) = ($o =~ /^([a-z\-]+)/);
82         $key =~ s/-//g;
83         my $arg = 'git-repo-config';
84         $arg .= ' --int' if ($o =~ /=i$/);
85         $arg .= ' --bool' if ($o !~ /=[sfi]$/);
86         if (ref $v eq 'ARRAY') {
87                 chomp(my @tmp = `$arg --get-all svn.$key`);
88                 @$v = @tmp if @tmp;
89         } else {
90                 chomp(my $tmp = `$arg --get svn.$key`);
91                 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
92                         $$v = $tmp;
93                 }
94         }
95 }
96
97 GetOptions(%opts, 'help|H|h' => \$_help,
98                 'version|V' => \$_version,
99                 'id|i=s' => \$GIT_SVN) or exit 1;
100
101 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
102 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
103 $SVN_URL = undef;
104 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
105 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
106
107 usage(0) if $_help;
108 version() if $_version;
109 usage(1) unless defined $cmd;
110 load_authors() if $_authors;
111 svn_compat_check();
112 $cmd{$cmd}->[0]->(@ARGV);
113 exit 0;
114
115 ####################### primary functions ######################
116 sub usage {
117         my $exit = shift || 0;
118         my $fd = $exit ? \*STDERR : \*STDOUT;
119         print $fd <<"";
120 git-svn - bidirectional operations between a single Subversion tree and git
121 Usage: $0 <command> [options] [arguments]\n
122
123         print $fd "Available commands:\n" unless $cmd;
124
125         foreach (sort keys %cmd) {
126                 next if $cmd && $cmd ne $_;
127                 print $fd '  ',pack('A13',$_),$cmd{$_}->[1],"\n";
128                 foreach (keys %{$cmd{$_}->[2]}) {
129                         # prints out arguments as they should be passed:
130                         my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
131                         print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
132                                                         "--$_" : "-$_" }
133                                                 split /\|/,$_)," $x\n";
134                 }
135         }
136         print $fd <<"";
137 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
138 arbitrary identifier if you're tracking multiple SVN branches/repositories in
139 one git repository and want to keep them separate.  See git-svn(1) for more
140 information.
141
142         exit $exit;
143 }
144
145 sub version {
146         print "git-svn version $VERSION\n";
147         exit 0;
148 }
149
150 sub rebuild {
151         $SVN_URL = shift or undef;
152         my $newest_rev = 0;
153         if ($_upgrade) {
154                 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
155         } else {
156                 check_upgrade_needed();
157         }
158
159         my $pid = open(my $rev_list,'-|');
160         defined $pid or croak $!;
161         if ($pid == 0) {
162                 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
163         }
164         my $latest;
165         while (<$rev_list>) {
166                 chomp;
167                 my $c = $_;
168                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
169                 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
170                 next if (!@commit); # skip merges
171                 my $id = $commit[$#commit];
172                 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
173                                                 \s([a-f\d\-]+)$/x);
174                 if (!$rev || !$uuid || !$url) {
175                         # some of the original repositories I made had
176                         # indentifiers like this:
177                         ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
178                                                         \@([a-f\d\-]+)/x);
179                         if (!$rev || !$uuid) {
180                                 croak "Unable to extract revision or UUID from ",
181                                         "$c, $id\n";
182                         }
183                 }
184
185                 # if we merged or otherwise started elsewhere, this is
186                 # how we break out of it
187                 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
188                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
189
190                 print "r$rev = $c\n";
191                 unless (defined $latest) {
192                         if (!$SVN_URL && !$url) {
193                                 croak "SVN repository location required: $url\n";
194                         }
195                         $SVN_URL ||= $url;
196                         $SVN_UUID ||= $uuid;
197                         setup_git_svn();
198                         $latest = $rev;
199                 }
200                 assert_revision_eq_or_unknown($rev, $c);
201                 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
202                 $newest_rev = $rev if ($rev > $newest_rev);
203         }
204         close $rev_list or croak $?;
205         if (!chdir $SVN_WC) {
206                 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
207                 chdir $SVN_WC or croak $!;
208         }
209
210         $pid = fork;
211         defined $pid or croak $!;
212         if ($pid == 0) {
213                 my @svn_up = qw(svn up);
214                 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
215                 sys(@svn_up,"-r$newest_rev");
216                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
217                 index_changes();
218                 exec('git-write-tree');
219         }
220         waitpid $pid, 0;
221
222         if ($_upgrade) {
223                 print STDERR <<"";
224 Keeping deprecated refs/head/$GIT_SVN-HEAD for now.  Please remove it
225 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
226
227         }
228 }
229
230 sub init {
231         $SVN_URL = shift or die "SVN repository location required " .
232                                 "as a command-line argument\n";
233         unless (-d $GIT_DIR) {
234                 sys('git-init-db');
235         }
236         setup_git_svn();
237 }
238
239 sub fetch {
240         my (@parents) = @_;
241         check_upgrade_needed();
242         $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
243         my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
244         unless ($_revision) {
245                 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
246         }
247         push @log_args, "-r$_revision";
248         push @log_args, '--stop-on-copy' unless $_no_stop_copy;
249
250         my $svn_log = svn_log_raw(@log_args);
251
252         my $base = next_log_entry($svn_log) or croak "No base revision!\n";
253         my $last_commit = undef;
254         unless (-d $SVN_WC) {
255                 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
256                 chdir $SVN_WC or croak $!;
257                 read_uuid();
258                 $last_commit = git_commit($base, @parents);
259                 assert_tree($last_commit);
260         } else {
261                 chdir $SVN_WC or croak $!;
262                 read_uuid();
263                 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
264         }
265         my @svn_up = qw(svn up);
266         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
267         my $last = $base;
268         while (my $log_msg = next_log_entry($svn_log)) {
269                 assert_tree($last_commit);
270                 if ($last->{revision} >= $log_msg->{revision}) {
271                         croak "Out of order: last >= current: ",
272                                 "$last->{revision} >= $log_msg->{revision}\n";
273                 }
274                 # Revert is needed for cases like:
275                 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
276                 # I can't seem to reproduce something like that on a test...
277                 sys(qw/svn revert -R ./);
278                 assert_svn_wc_clean($last->{revision});
279                 sys(@svn_up,"-r$log_msg->{revision}");
280                 $last_commit = git_commit($log_msg, $last_commit, @parents);
281                 $last = $log_msg;
282         }
283         unless (-e "$GIT_DIR/refs/heads/master") {
284                 sys(qw(git-update-ref refs/heads/master),$last_commit);
285         }
286         return $last;
287 }
288
289 sub commit {
290         my (@commits) = @_;
291         check_upgrade_needed();
292         if ($_stdin || !@commits) {
293                 print "Reading from stdin...\n";
294                 @commits = ();
295                 while (<STDIN>) {
296                         if (/\b($sha1_short)\b/o) {
297                                 unshift @commits, $1;
298                         }
299                 }
300         }
301         my @revs;
302         foreach my $c (@commits) {
303                 chomp(my @tmp = safe_qx('git-rev-parse',$c));
304                 if (scalar @tmp == 1) {
305                         push @revs, $tmp[0];
306                 } elsif (scalar @tmp > 1) {
307                         push @revs, reverse (safe_qx('git-rev-list',@tmp));
308                 } else {
309                         die "Failed to rev-parse $c\n";
310                 }
311         }
312         chomp @revs;
313
314         chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
315         my $info = svn_info('.');
316         my $fetched = fetch();
317         if ($info->{Revision} != $fetched->{revision}) {
318                 print STDERR "There are new revisions that were fetched ",
319                                 "and need to be merged (or acknowledged) ",
320                                 "before committing.\n";
321                 exit 1;
322         }
323         $info = svn_info('.');
324         read_uuid($info);
325         my $svn_current_rev =  $info->{'Last Changed Rev'};
326         foreach my $c (@revs) {
327                 my $mods = svn_checkout_tree($svn_current_rev, $c);
328                 if (scalar @$mods == 0) {
329                         print "Skipping, no changes detected\n";
330                         next;
331                 }
332                 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
333         }
334         print "Done committing ",scalar @revs," revisions to SVN\n";
335 }
336
337 sub show_ignore {
338         require File::Find or die $!;
339         my $exclude_file = "$GIT_DIR/info/exclude";
340         open my $fh, '<', $exclude_file or croak $!;
341         chomp(my @excludes = (<$fh>));
342         close $fh or croak $!;
343
344         $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
345         chdir $SVN_WC or croak $!;
346         my %ign;
347         File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
348                 s#^\./##;
349                 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
350                 }}, no_chdir=>1},'.');
351
352         print "\n# /\n";
353         foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
354         delete $ign{'.'};
355         foreach my $i (sort keys %ign) {
356                 print "\n# ",$i,"\n";
357                 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
358         }
359 }
360
361 ########################### utility functions #########################
362
363 sub read_uuid {
364         return if $SVN_UUID;
365         my $info = shift || svn_info('.');
366         $SVN_UUID = $info->{'Repository UUID'} or
367                                         croak "Repository UUID unreadable\n";
368         s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
369 }
370
371 sub setup_git_svn {
372         defined $SVN_URL or croak "SVN repository location required\n";
373         unless (-d $GIT_DIR) {
374                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
375         }
376         mkpath(["$GIT_DIR/$GIT_SVN"]);
377         mkpath(["$GIT_DIR/$GIT_SVN/info"]);
378         mkpath([$REV_DIR]);
379         s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
380
381         open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
382         print $fd '.svn',"\n";
383         close $fd or croak $!;
384 }
385
386 sub assert_svn_wc_clean {
387         my ($svn_rev) = @_;
388         croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
389         my $lcr = svn_info('.')->{'Last Changed Rev'};
390         if ($svn_rev != $lcr) {
391                 print STDERR "Checking for copy-tree ... ";
392                 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
393                                                 "-r$lcr:$svn_rev")));
394                 if (@diff) {
395                         croak "Nope!  Expected r$svn_rev, got r$lcr\n";
396                 } else {
397                         print STDERR "OK!\n";
398                 }
399         }
400         my @status = grep(!/^Performing status on external/,(`svn status`));
401         @status = grep(!/^\s*$/,@status);
402         if (scalar @status) {
403                 print STDERR "Tree ($SVN_WC) is not clean:\n";
404                 print STDERR $_ foreach @status;
405                 croak;
406         }
407 }
408
409 sub assert_tree {
410         my ($treeish) = @_;
411         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
412         chomp(my $type = `git-cat-file -t $treeish`);
413         my $expected;
414         while ($type eq 'tag') {
415                 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
416         }
417         if ($type eq 'commit') {
418                 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
419                 ($expected) = ($expected =~ /^tree ($sha1)$/);
420                 die "Unable to get tree from $treeish\n" unless $expected;
421         } elsif ($type eq 'tree') {
422                 $expected = $treeish;
423         } else {
424                 die "$treeish is a $type, expected tree, tag or commit\n";
425         }
426
427         my $old_index = $ENV{GIT_INDEX_FILE};
428         my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
429         if (-e $tmpindex) {
430                 unlink $tmpindex or croak $!;
431         }
432         $ENV{GIT_INDEX_FILE} = $tmpindex;
433         index_changes(1);
434         chomp(my $tree = `git-write-tree`);
435         if ($old_index) {
436                 $ENV{GIT_INDEX_FILE} = $old_index;
437         } else {
438                 delete $ENV{GIT_INDEX_FILE};
439         }
440         if ($tree ne $expected) {
441                 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
442         }
443         unlink $tmpindex;
444 }
445
446 sub parse_diff_tree {
447         my $diff_fh = shift;
448         local $/ = "\0";
449         my $state = 'meta';
450         my @mods;
451         while (<$diff_fh>) {
452                 chomp $_; # this gets rid of the trailing "\0"
453                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
454                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
455                         push @mods, {   mode_a => $1, mode_b => $2,
456                                         sha1_b => $3, chg => $4 };
457                         if ($4 =~ /^(?:C|R)$/) {
458                                 $state = 'file_a';
459                         } else {
460                                 $state = 'file_b';
461                         }
462                 } elsif ($state eq 'file_a') {
463                         my $x = $mods[$#mods] or croak "Empty array\n";
464                         if ($x->{chg} !~ /^(?:C|R)$/) {
465                                 croak "Error parsing $_, $x->{chg}\n";
466                         }
467                         $x->{file_a} = $_;
468                         $state = 'file_b';
469                 } elsif ($state eq 'file_b') {
470                         my $x = $mods[$#mods] or croak "Empty array\n";
471                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
472                                 croak "Error parsing $_, $x->{chg}\n";
473                         }
474                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
475                                 croak "Error parsing $_, $x->{chg}\n";
476                         }
477                         $x->{file_b} = $_;
478                         $state = 'meta';
479                 } else {
480                         croak "Error parsing $_\n";
481                 }
482         }
483         close $diff_fh or croak $!;
484
485         return \@mods;
486 }
487
488 sub svn_check_prop_executable {
489         my $m = shift;
490         return if -l $m->{file_b};
491         if ($m->{mode_b} =~ /755$/) {
492                 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
493                 if ($m->{mode_a} !~ /755$/) {
494                         sys(qw(svn propset svn:executable 1), $m->{file_b});
495                 }
496                 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
497         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
498                 sys(qw(svn propdel svn:executable), $m->{file_b});
499                 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
500                 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
501         }
502 }
503
504 sub svn_ensure_parent_path {
505         my $dir_b = dirname(shift);
506         svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
507         mkpath([$dir_b]) unless (-d $dir_b);
508         sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
509 }
510
511 sub precommit_check {
512         my $mods = shift;
513         my (%rm_file, %rmdir_check, %added_check);
514
515         my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
516         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
517                 if ($m->{chg} eq 'R') {
518                         if (-d $m->{file_b}) {
519                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
520                         }
521                         # dir/$file => dir/file/$file
522                         my $dirname = dirname($m->{file_b});
523                         while ($dirname ne File::Spec->curdir) {
524                                 if ($dirname ne $m->{file_a}) {
525                                         $dirname = dirname($dirname);
526                                         next;
527                                 }
528                                 err_file_to_dir("$m->{file_a} => $m->{file_b}");
529                         }
530                         # baz/zzz => baz (baz is a file)
531                         $dirname = dirname($m->{file_a});
532                         while ($dirname ne File::Spec->curdir) {
533                                 if ($dirname ne $m->{file_b}) {
534                                         $dirname = dirname($dirname);
535                                         next;
536                                 }
537                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
538                         }
539                 }
540                 if ($m->{chg} =~ /^(D|R)$/) {
541                         my $t = $1 eq 'D' ? 'file_b' : 'file_a';
542                         $rm_file{ $m->{$t} } = 1;
543                         my $dirname = dirname( $m->{$t} );
544                         my $basename = basename( $m->{$t} );
545                         $rmdir_check{$dirname}->{$basename} = 1;
546                 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
547                         if (-d $m->{file_b}) {
548                                 err_dir_to_file($m->{file_b});
549                         }
550                         my $dirname = dirname( $m->{file_b} );
551                         my $basename = basename( $m->{file_b} );
552                         $added_check{$dirname}->{$basename} = 1;
553                         while ($dirname ne File::Spec->curdir) {
554                                 if ($rm_file{$dirname}) {
555                                         err_file_to_dir($m->{file_b});
556                                 }
557                                 $dirname = dirname $dirname;
558                         }
559                 }
560         }
561         return (\%rmdir_check, \%added_check);
562
563         sub err_dir_to_file {
564                 my $file = shift;
565                 print STDERR "Node change from directory to file ",
566                                 "is not supported by Subversion: ",$file,"\n";
567                 exit 1;
568         }
569         sub err_file_to_dir {
570                 my $file = shift;
571                 print STDERR "Node change from file to directory ",
572                                 "is not supported by Subversion: ",$file,"\n";
573                 exit 1;
574         }
575 }
576
577 sub svn_checkout_tree {
578         my ($svn_rev, $treeish) = @_;
579         my $from = file_to_s("$REV_DIR/$svn_rev");
580         assert_tree($from);
581         print "diff-tree $from $treeish\n";
582         my $pid = open my $diff_fh, '-|';
583         defined $pid or croak $!;
584         if ($pid == 0) {
585                 my @diff_tree = qw(git-diff-tree -z -r);
586                 if ($_cp_similarity) {
587                         push @diff_tree, "-C$_cp_similarity";
588                 } else {
589                         push @diff_tree, '-C';
590                 }
591                 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
592                 push @diff_tree, "-l$_l" if defined $_l;
593                 exec(@diff_tree, $from, $treeish) or croak $!;
594         }
595         my $mods = parse_diff_tree($diff_fh);
596         unless (@$mods) {
597                 # git can do empty commits, but SVN doesn't allow it...
598                 return $mods;
599         }
600         my ($rm, $add) = precommit_check($mods);
601
602         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
603         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
604                 if ($m->{chg} eq 'C') {
605                         svn_ensure_parent_path( $m->{file_b} );
606                         sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
607                         apply_mod_line_blob($m);
608                         svn_check_prop_executable($m);
609                 } elsif ($m->{chg} eq 'D') {
610                         sys(qw(svn rm --force), $m->{file_b});
611                 } elsif ($m->{chg} eq 'R') {
612                         svn_ensure_parent_path( $m->{file_b} );
613                         sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
614                         apply_mod_line_blob($m);
615                         svn_check_prop_executable($m);
616                 } elsif ($m->{chg} eq 'M') {
617                         apply_mod_line_blob($m);
618                         svn_check_prop_executable($m);
619                 } elsif ($m->{chg} eq 'T') {
620                         sys(qw(svn rm --force),$m->{file_b});
621                         apply_mod_line_blob($m);
622                         sys(qw(svn add --force), $m->{file_b});
623                         svn_check_prop_executable($m);
624                 } elsif ($m->{chg} eq 'A') {
625                         svn_ensure_parent_path( $m->{file_b} );
626                         apply_mod_line_blob($m);
627                         sys(qw(svn add --force), $m->{file_b});
628                         svn_check_prop_executable($m);
629                 } else {
630                         croak "Invalid chg: $m->{chg}\n";
631                 }
632         }
633
634         assert_tree($treeish);
635         if ($_rmdir) { # remove empty directories
636                 handle_rmdir($rm, $add);
637         }
638         assert_tree($treeish);
639         return $mods;
640 }
641
642 # svn ls doesn't work with respect to the current working tree, but what's
643 # in the repository.  There's not even an option for it... *sigh*
644 # (added files don't show up and removed files remain in the ls listing)
645 sub svn_ls_current {
646         my ($dir, $rm, $add) = @_;
647         chomp(my @ls = safe_qx('svn','ls',$dir));
648         my @ret = ();
649         foreach (@ls) {
650                 s#/$##; # trailing slashes are evil
651                 push @ret, $_ unless $rm->{$dir}->{$_};
652         }
653         if (exists $add->{$dir}) {
654                 push @ret, keys %{$add->{$dir}};
655         }
656         return \@ret;
657 }
658
659 sub handle_rmdir {
660         my ($rm, $add) = @_;
661
662         foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
663                 my $ls = svn_ls_current($dir, $rm, $add);
664                 next if (scalar @$ls);
665                 sys(qw(svn rm --force),$dir);
666
667                 my $dn = dirname $dir;
668                 $rm->{ $dn }->{ basename $dir } = 1;
669                 $ls = svn_ls_current($dn, $rm, $add);
670                 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
671                         sys(qw(svn rm --force),$dn);
672                         $dir = basename $dn;
673                         $dn = dirname $dn;
674                         $rm->{ $dn }->{ $dir } = 1;
675                         $ls = svn_ls_current($dn, $rm, $add);
676                 }
677         }
678 }
679
680 sub svn_commit_tree {
681         my ($svn_rev, $commit) = @_;
682         my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
683         my %log_msg = ( msg => '' );
684         open my $msg, '>', $commit_msg or croak $!;
685
686         chomp(my $type = `git-cat-file -t $commit`);
687         if ($type eq 'commit') {
688                 my $pid = open my $msg_fh, '-|';
689                 defined $pid or croak $!;
690
691                 if ($pid == 0) {
692                         exec(qw(git-cat-file commit), $commit) or croak $!;
693                 }
694                 my $in_msg = 0;
695                 while (<$msg_fh>) {
696                         if (!$in_msg) {
697                                 $in_msg = 1 if (/^\s*$/);
698                         } elsif (/^git-svn-id: /) {
699                                 # skip this, we regenerate the correct one
700                                 # on re-fetch anyways
701                         } else {
702                                 print $msg $_ or croak $!;
703                         }
704                 }
705                 close $msg_fh or croak $!;
706         }
707         close $msg or croak $!;
708
709         if ($_edit || ($type eq 'tree')) {
710                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
711                 system($editor, $commit_msg);
712         }
713
714         # file_to_s removes all trailing newlines, so just use chomp() here:
715         open $msg, '<', $commit_msg or croak $!;
716         { local $/; chomp($log_msg{msg} = <$msg>); }
717         close $msg or croak $!;
718
719         my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
720         print "Committing $commit: $oneline\n";
721
722         if (defined $LC_ALL) {
723                 $ENV{LC_ALL} = $LC_ALL;
724         } else {
725                 delete $ENV{LC_ALL};
726         }
727         my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
728         $ENV{LC_ALL} = 'C';
729         unlink $commit_msg;
730         my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
731         if (!defined $committed) {
732                 my $out = join("\n",@ci_output);
733                 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
734                                 $out, "\n\nAssuming English locale...";
735                 ($committed) = ($out =~ /^Committed revision \d+\./sm);
736                 defined $committed or die " FAILED!\n",
737                         "Commit output failed to parse committed revision!\n",
738                 print STDERR " OK\n";
739         }
740
741         my @svn_up = qw(svn up);
742         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
743         if ($committed == ($svn_rev + 1)) {
744                 push @svn_up, "-r$committed";
745                 sys(@svn_up);
746                 my $info = svn_info('.');
747                 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
748                 if ($info->{'Last Changed Rev'} != $committed) {
749                         croak "$info->{'Last Changed Rev'} != $committed\n"
750                 }
751                 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
752                                         /(\d{4})\-(\d\d)\-(\d\d)\s
753                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
754                                          or croak "Failed to parse date: $date\n";
755                 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
756                 $log_msg{author} = $info->{'Last Changed Author'};
757                 $log_msg{revision} = $committed;
758                 $log_msg{msg} .= "\n";
759                 my $parent = file_to_s("$REV_DIR/$svn_rev");
760                 git_commit(\%log_msg, $parent, $commit);
761                 return $committed;
762         }
763         # resync immediately
764         push @svn_up, "-r$svn_rev";
765         sys(@svn_up);
766         return fetch("$committed=$commit")->{revision};
767 }
768
769 # read the entire log into a temporary file (which is removed ASAP)
770 # and store the file handle + parser state
771 sub svn_log_raw {
772         my (@log_args) = @_;
773         my $log_fh = IO::File->new_tmpfile or croak $!;
774         my $pid = fork;
775         defined $pid or croak $!;
776         if (!$pid) {
777                 open STDOUT, '>&', $log_fh or croak $!;
778                 exec (qw(svn log), @log_args) or croak $!
779         }
780         waitpid $pid, 0;
781         croak if $?;
782         seek $log_fh, 0, 0 or croak $!;
783         return { state => 'sep', fh => $log_fh };
784 }
785
786 sub next_log_entry {
787         my $log = shift; # retval of svn_log_raw()
788         my $ret = undef;
789         my $fh = $log->{fh};
790
791         while (<$fh>) {
792                 chomp;
793                 if (/^\-{72}$/) {
794                         if ($log->{state} eq 'msg') {
795                                 if ($ret->{lines}) {
796                                         $ret->{msg} .= $_."\n";
797                                         unless(--$ret->{lines}) {
798                                                 $log->{state} = 'sep';
799                                         }
800                                 } else {
801                                         croak "Log parse error at: $_\n",
802                                                 $ret->{revision},
803                                                 "\n";
804                                 }
805                                 next;
806                         }
807                         if ($log->{state} ne 'sep') {
808                                 croak "Log parse error at: $_\n",
809                                         "state: $log->{state}\n",
810                                         $ret->{revision},
811                                         "\n";
812                         }
813                         $log->{state} = 'rev';
814
815                         # if we have an empty log message, put something there:
816                         if ($ret) {
817                                 $ret->{msg} ||= "\n";
818                                 delete $ret->{lines};
819                                 return $ret;
820                         }
821                         next;
822                 }
823                 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
824                         my $rev = $1;
825                         my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
826                         ($lines) = ($lines =~ /(\d+)/);
827                         my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
828                                         /(\d{4})\-(\d\d)\-(\d\d)\s
829                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
830                                          or croak "Failed to parse date: $date\n";
831                         $ret = {        revision => $rev,
832                                         date => "$tz $Y-$m-$d $H:$M:$S",
833                                         author => $author,
834                                         lines => $lines,
835                                         msg => '' };
836                         if (defined $_authors && ! defined $users{$author}) {
837                                 die "Author: $author not defined in ",
838                                                 "$_authors file\n";
839                         }
840                         $log->{state} = 'msg_start';
841                         next;
842                 }
843                 # skip the first blank line of the message:
844                 if ($log->{state} eq 'msg_start' && /^$/) {
845                         $log->{state} = 'msg';
846                 } elsif ($log->{state} eq 'msg') {
847                         if ($ret->{lines}) {
848                                 $ret->{msg} .= $_."\n";
849                                 unless (--$ret->{lines}) {
850                                         $log->{state} = 'sep';
851                                 }
852                         } else {
853                                 croak "Log parse error at: $_\n",
854                                         $ret->{revision},"\n";
855                         }
856                 }
857         }
858         return $ret;
859 }
860
861 sub svn_info {
862         my $url = shift || $SVN_URL;
863
864         my $pid = open my $info_fh, '-|';
865         defined $pid or croak $!;
866
867         if ($pid == 0) {
868                 exec(qw(svn info),$url) or croak $!;
869         }
870
871         my $ret = {};
872         # only single-lines seem to exist in svn info output
873         while (<$info_fh>) {
874                 chomp $_;
875                 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
876                         $ret->{$1} = $2;
877                         push @{$ret->{-order}}, $1;
878                 }
879         }
880         close $info_fh or croak $!;
881         return $ret;
882 }
883
884 sub sys { system(@_) == 0 or croak $? }
885
886 sub eol_cp {
887         my ($from, $to) = @_;
888         my $es = svn_propget_base('svn:eol-style', $to);
889         open my $rfd, '<', $from or croak $!;
890         binmode $rfd or croak $!;
891         open my $wfd, '>', $to or croak $!;
892         binmode $wfd or croak $!;
893
894         my $eol = $EOL{$es} or undef;
895         my $buf;
896         use bytes;
897         while (1) {
898                 my ($r, $w, $t);
899                 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
900                 return unless $r;
901                 if ($eol) {
902                         if ($buf =~ /\015$/) {
903                                 my $c;
904                                 defined($r = sysread($rfd,$c,1)) or croak $!;
905                                 $buf .= $c if $r > 0;
906                         }
907                         $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
908                         $r = length($buf);
909                 }
910                 for ($w = 0; $w < $r; $w += $t) {
911                         $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
912                 }
913         }
914         no bytes;
915 }
916
917 sub do_update_index {
918         my ($z_cmd, $cmd, $no_text_base) = @_;
919
920         my $z = open my $p, '-|';
921         defined $z or croak $!;
922         unless ($z) { exec @$z_cmd or croak $! }
923
924         my $pid = open my $ui, '|-';
925         defined $pid or croak $!;
926         unless ($pid) {
927                 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
928         }
929         local $/ = "\0";
930         while (my $x = <$p>) {
931                 chomp $x;
932                 if (!$no_text_base && lstat $x && ! -l _ &&
933                                 svn_propget_base('svn:keywords', $x)) {
934                         my $mode = -x _ ? 0755 : 0644;
935                         my ($v,$d,$f) = File::Spec->splitpath($x);
936                         my $tb = File::Spec->catfile($d, '.svn', 'tmp',
937                                                 'text-base',"$f.svn-base");
938                         $tb =~ s#^/##;
939                         unless (-f $tb) {
940                                 $tb = File::Spec->catfile($d, '.svn',
941                                                 'text-base',"$f.svn-base");
942                                 $tb =~ s#^/##;
943                         }
944                         unlink $x or croak $!;
945                         eol_cp($tb, $x);
946                         chmod(($mode &~ umask), $x) or croak $!;
947                 }
948                 print $ui $x,"\0";
949         }
950         close $ui or croak $!;
951 }
952
953 sub index_changes {
954         my $no_text_base = shift;
955         do_update_index([qw/git-diff-files --name-only -z/],
956                         'remove',
957                         $no_text_base);
958         do_update_index([qw/git-ls-files -z --others/,
959                               "--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude"],
960                         'add',
961                         $no_text_base);
962 }
963
964 sub s_to_file {
965         my ($str, $file, $mode) = @_;
966         open my $fd,'>',$file or croak $!;
967         print $fd $str,"\n" or croak $!;
968         close $fd or croak $!;
969         chmod ($mode &~ umask, $file) if (defined $mode);
970 }
971
972 sub file_to_s {
973         my $file = shift;
974         open my $fd,'<',$file or croak "$!: file: $file\n";
975         local $/;
976         my $ret = <$fd>;
977         close $fd or croak $!;
978         $ret =~ s/\s*$//s;
979         return $ret;
980 }
981
982 sub assert_revision_unknown {
983         my $revno = shift;
984         if (-f "$REV_DIR/$revno") {
985                 croak "$REV_DIR/$revno already exists! ",
986                                 "Why are we refetching it?";
987         }
988 }
989
990 sub trees_eq {
991         my ($x, $y) = @_;
992         my @x = safe_qx('git-cat-file','commit',$x);
993         my @y = safe_qx('git-cat-file','commit',$y);
994         if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
995                                 || $y[0] !~ /^tree $sha1\n$/) {
996                 print STDERR "Trees not equal: $y[0] != $x[0]\n";
997                 return 0
998         }
999         return 1;
1000 }
1001
1002 sub assert_revision_eq_or_unknown {
1003         my ($revno, $commit) = @_;
1004         if (-f "$REV_DIR/$revno") {
1005                 my $current = file_to_s("$REV_DIR/$revno");
1006                 if (($commit ne $current) && !trees_eq($commit, $current)) {
1007                         croak "$REV_DIR/$revno already exists!\n",
1008                                 "current: $current\nexpected: $commit\n";
1009                 }
1010                 return;
1011         }
1012 }
1013
1014 sub git_commit {
1015         my ($log_msg, @parents) = @_;
1016         assert_revision_unknown($log_msg->{revision});
1017         my $out_fh = IO::File->new_tmpfile or croak $!;
1018
1019         map_tree_joins() if (@_branch_from && !%tree_map);
1020
1021         # commit parents can be conditionally bound to a particular
1022         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1023         my @exec_parents;
1024         foreach my $p (@parents) {
1025                 next unless defined $p;
1026                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1027                         if ($1 == $log_msg->{revision}) {
1028                                 push @exec_parents, $2;
1029                         }
1030                 } else {
1031                         push @exec_parents, $p if $p =~ /$sha1_short/o;
1032                 }
1033         }
1034
1035         my $pid = fork;
1036         defined $pid or croak $!;
1037         if ($pid == 0) {
1038                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
1039                 index_changes();
1040                 chomp(my $tree = `git-write-tree`);
1041                 croak if $?;
1042                 if (exists $tree_map{$tree}) {
1043                         my %seen_parent = map { $_ => 1 } @exec_parents;
1044                         foreach (@{$tree_map{$tree}}) {
1045                                 # MAXPARENT is defined to 16 in commit-tree.c:
1046                                 if ($seen_parent{$_} || @exec_parents > 16) {
1047                                         next;
1048                                 }
1049                                 push @exec_parents, $_;
1050                                 $seen_parent{$_} = 1;
1051                         }
1052                 }
1053                 my $msg_fh = IO::File->new_tmpfile or croak $!;
1054                 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1055                                         "$SVN_URL\@$log_msg->{revision}",
1056                                         " $SVN_UUID\n" or croak $!;
1057                 $msg_fh->flush == 0 or croak $!;
1058                 seek $msg_fh, 0, 0 or croak $!;
1059
1060                 set_commit_env($log_msg);
1061
1062                 my @exec = ('git-commit-tree',$tree);
1063                 push @exec, '-p', $_  foreach @exec_parents;
1064                 open STDIN, '<&', $msg_fh or croak $!;
1065                 open STDOUT, '>&', $out_fh or croak $!;
1066                 exec @exec or croak $!;
1067         }
1068         waitpid($pid,0);
1069         croak if $?;
1070
1071         $out_fh->flush == 0 or croak $!;
1072         seek $out_fh, 0, 0 or croak $!;
1073         chomp(my $commit = do { local $/; <$out_fh> });
1074         if ($commit !~ /^$sha1$/o) {
1075                 croak "Failed to commit, invalid sha1: $commit\n";
1076         }
1077         my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1078         if (my $primary_parent = shift @exec_parents) {
1079                 $pid = fork;
1080                 defined $pid or croak $!;
1081                 if (!$pid) {
1082                         close STDERR;
1083                         close STDOUT;
1084                         exec 'git-rev-parse','--verify',
1085                                                 "refs/remotes/$GIT_SVN^0";
1086                 }
1087                 waitpid $pid, 0;
1088                 push @update_ref, $primary_parent unless $?;
1089         }
1090         sys(@update_ref);
1091         sys('git-update-ref',"$GIT_SVN/revs/$log_msg->{revision}",$commit);
1092         print "r$log_msg->{revision} = $commit\n";
1093         return $commit;
1094 }
1095
1096 sub set_commit_env {
1097         my ($log_msg) = @_;
1098         my $author = $log_msg->{author};
1099         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1100                                 : ($author,"$author\@$SVN_UUID");
1101         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1102         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1103         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1104 }
1105
1106 sub apply_mod_line_blob {
1107         my $m = shift;
1108         if ($m->{mode_b} =~ /^120/) {
1109                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1110         } else {
1111                 blob_to_file($m->{sha1_b}, $m->{file_b});
1112         }
1113 }
1114
1115 sub blob_to_symlink {
1116         my ($blob, $link) = @_;
1117         defined $link or croak "\$link not defined!\n";
1118         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1119         if (-l $link || -f _) {
1120                 unlink $link or croak $!;
1121         }
1122
1123         my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1124         symlink $dest, $link or croak $!;
1125 }
1126
1127 sub blob_to_file {
1128         my ($blob, $file) = @_;
1129         defined $file or croak "\$file not defined!\n";
1130         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1131         if (-l $file || -f _) {
1132                 unlink $file or croak $!;
1133         }
1134
1135         open my $blob_fh, '>', $file or croak "$!: $file\n";
1136         my $pid = fork;
1137         defined $pid or croak $!;
1138
1139         if ($pid == 0) {
1140                 open STDOUT, '>&', $blob_fh or croak $!;
1141                 exec('git-cat-file','blob',$blob);
1142         }
1143         waitpid $pid, 0;
1144         croak $? if $?;
1145
1146         close $blob_fh or croak $!;
1147 }
1148
1149 sub safe_qx {
1150         my $pid = open my $child, '-|';
1151         defined $pid or croak $!;
1152         if ($pid == 0) {
1153                 exec(@_) or croak $?;
1154         }
1155         my @ret = (<$child>);
1156         close $child or croak $?;
1157         die $? if $?; # just in case close didn't error out
1158         return wantarray ? @ret : join('',@ret);
1159 }
1160
1161 sub svn_compat_check {
1162         my @co_help = safe_qx(qw(svn co -h));
1163         unless (grep /ignore-externals/,@co_help) {
1164                 print STDERR "W: Installed svn version does not support ",
1165                                 "--ignore-externals\n";
1166                 $_no_ignore_ext = 1;
1167         }
1168         if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1169                 $_svn_co_url_revs = 1;
1170         }
1171         if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1172                 $_svn_pg_peg_revs = 1;
1173         }
1174
1175         # I really, really hope nobody hits this...
1176         unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1177                 print STDERR <<'';
1178 W: The installed svn version does not support the --stop-on-copy flag in
1179    the log command.
1180    Lets hope the directory you're tracking is not a branch or tag
1181    and was never moved within the repository...
1182
1183                 $_no_stop_copy = 1;
1184         }
1185 }
1186
1187 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1188 # (and they won't honor URL@<rev> without -r<rev>, too!)
1189 sub svn_cmd_checkout {
1190         my ($url, $rev, $dir) = @_;
1191         my @cmd = ('svn','co', "-r$rev");
1192         push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1193         $url .= "\@$rev" if $_svn_co_url_revs;
1194         sys(@cmd, $url, $dir);
1195 }
1196
1197 sub check_upgrade_needed {
1198         my $old = eval {
1199                 my $pid = open my $child, '-|';
1200                 defined $pid or croak $!;
1201                 if ($pid == 0) {
1202                         close STDERR;
1203                         exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1204                 }
1205                 my @ret = (<$child>);
1206                 close $child or croak $?;
1207                 die $? if $?; # just in case close didn't error out
1208                 return wantarray ? @ret : join('',@ret);
1209         };
1210         return unless $old;
1211         my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1212         if ($@ || !$head) {
1213                 print STDERR "Please run: $0 rebuild --upgrade\n";
1214                 exit 1;
1215         }
1216 }
1217
1218 # fills %tree_map with a reverse mapping of trees to commits.  Useful
1219 # for finding parents to commit on.
1220 sub map_tree_joins {
1221         foreach my $br (@_branch_from) {
1222                 my $pid = open my $pipe, '-|';
1223                 defined $pid or croak $!;
1224                 if ($pid == 0) {
1225                         exec(qw(git-rev-list --pretty=raw), $br) or croak $?;
1226                 }
1227                 while (<$pipe>) {
1228                         if (/^commit ($sha1)$/o) {
1229                                 my $commit = $1;
1230                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1231                                 unless (defined $tree) {
1232                                         die "Failed to parse commit $commit\n";
1233                                 }
1234                                 push @{$tree_map{$tree}}, $commit;
1235                         }
1236                 }
1237                 close $pipe or croak $?;
1238         }
1239 }
1240
1241 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1242 sub load_authors {
1243         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1244         while (<$authors>) {
1245                 chomp;
1246                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1247                 my ($user, $name, $email) = ($1, $2, $3);
1248                 $users{$user} = [$name, $email];
1249         }
1250         close $authors or croak $!;
1251 }
1252
1253 sub svn_propget_base {
1254         my ($p, $f) = @_;
1255         $f .= '@BASE' if $_svn_pg_peg_revs;
1256         return safe_qx(qw/svn propget/, $p, $f);
1257 }
1258
1259 __END__
1260
1261 Data structures:
1262
1263 $svn_log hashref (as returned by svn_log_raw)
1264 {
1265         fh => file handle of the log file,
1266         state => state of the log file parser (sep/msg/rev/msg_start...)
1267 }
1268
1269 $log_msg hashref as returned by next_log_entry($svn_log)
1270 {
1271         msg => 'whitespace-formatted log entry
1272 ',                                              # trailing newline is preserved
1273         revision => '8',                        # integer
1274         date => '2004-02-24T17:01:44.108345Z',  # commit date
1275         author => 'committer name'
1276 };
1277
1278
1279 @mods = array of diff-index line hashes, each element represents one line
1280         of diff-index output
1281
1282 diff-index line ($m hash)
1283 {
1284         mode_a => first column of diff-index output, no leading ':',
1285         mode_b => second column of diff-index output,
1286         sha1_b => sha1sum of the final blob,
1287         chg => change type [MCRADT],
1288         file_a => original file name of a file (iff chg is 'C' or 'R')
1289         file_b => new/current file name of a file (any chg)
1290 }
1291 ;