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