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