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