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