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