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