808b93399300179ed772b251f8c1e426086ca7f5
1#!/usr/bin/env perl
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $REV_DIR/;
10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11$VERSION = '0.10.0';
12$GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
13# make sure the svn binary gives consistent output between locales and TZs:
14$ENV{TZ} = 'UTC';
15$ENV{LC_ALL} = 'C';
16
17# If SVN:: library support is added, please make the dependencies
18# optional and preserve the capability to use the command-line client.
19# use eval { require SVN::... } to make it lazy load
20# We don't use any modules not in the standard Perl distribution:
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//;
27use POSIX qw/strftime/;
28my $sha1 = qr/[a-f\d]{40}/;
29my $sha1_short = qr/[a-f\d]{4,40}/;
30my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
31 $_find_copies_harder, $_l, $_version, $_upgrade, $_authors);
32my (@_branch_from, %tree_map, %users);
33
34my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
35 'branch|b=s' => \@_branch_from,
36 'authors-file|A=s' => \$_authors );
37my %cmd = (
38 fetch => [ \&fetch, "Download new revisions from SVN",
39 { 'revision|r=s' => \$_revision, %fc_opts } ],
40 init => [ \&init, "Initialize and fetch (import)", { } ],
41 commit => [ \&commit, "Commit git revisions to SVN",
42 { 'stdin|' => \$_stdin,
43 'edit|e' => \$_edit,
44 'rmdir' => \$_rmdir,
45 'find-copies-harder' => \$_find_copies_harder,
46 'l=i' => \$_l,
47 %fc_opts,
48 } ],
49 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
50 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
51 { 'no-ignore-externals' => \$_no_ignore_ext,
52 'upgrade' => \$_upgrade } ],
53);
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
63my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
64
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
76usage(0) if $_help;
77version() if $_version;
78usage(1) unless defined $cmd;
79load_authors() if $_authors;
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
91
92 print $fd "Available commands:\n" unless $cmd;
93
94 foreach (sort keys %cmd) {
95 next if $cmd && $cmd ne $_;
96 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
97 foreach (keys %{$cmd{$_}->[2]}) {
98 # prints out arguments as they should be passed:
99 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
100 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
101 "--$_" : "-$_" }
102 split /\|/,$_)," $x\n";
103 }
104 }
105 print $fd <<"";
106\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
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.
110
111 exit $exit;
112}
113
114sub version {
115 print "git-svn version $VERSION\n";
116 exit 0;
117}
118
119sub rebuild {
120 $SVN_URL = shift or undef;
121 my $newest_rev = 0;
122 if ($_upgrade) {
123 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
124 } else {
125 check_upgrade_needed();
126 }
127
128 my $pid = open(my $rev_list,'-|');
129 defined $pid or croak $!;
130 if ($pid == 0) {
131 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
132 }
133 my $latest;
134 while (<$rev_list>) {
135 chomp;
136 my $c = $_;
137 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
138 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
139 next if (!@commit); # skip merges
140 my $id = $commit[$#commit];
141 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
142 \s([a-f\d\-]+)$/x);
143 if (!$rev || !$uuid || !$url) {
144 # some of the original repositories I made had
145 # indentifiers like this:
146 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
147 \@([a-f\d\-]+)/x);
148 if (!$rev || !$uuid) {
149 croak "Unable to extract revision or UUID from ",
150 "$c, $id\n";
151 }
152 }
153
154 # if we merged or otherwise started elsewhere, this is
155 # how we break out of it
156 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
157 next if (defined $SVN_URL && ($url ne $SVN_URL));
158
159 print "r$rev = $c\n";
160 unless (defined $latest) {
161 if (!$SVN_URL && !$url) {
162 croak "SVN repository location required: $url\n";
163 }
164 $SVN_URL ||= $url;
165 $SVN_UUID ||= setup_git_svn();
166 $latest = $rev;
167 }
168 assert_revision_eq_or_unknown($rev, $c);
169 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
170 $newest_rev = $rev if ($rev > $newest_rev);
171 }
172 close $rev_list or croak $?;
173 if (!chdir $SVN_WC) {
174 my @svn_co = ('svn','co',"-r$latest");
175 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
176 sys(@svn_co, $SVN_URL, $SVN_WC);
177 chdir $SVN_WC or croak $!;
178 }
179
180 $pid = fork;
181 defined $pid or croak $!;
182 if ($pid == 0) {
183 my @svn_up = qw(svn up);
184 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
185 sys(@svn_up,"-r$newest_rev");
186 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
187 git_addremove();
188 exec('git-write-tree');
189 }
190 waitpid $pid, 0;
191
192 if ($_upgrade) {
193 print STDERR <<"";
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 }
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) = @_;
210 check_upgrade_needed();
211 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
212 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
213 unless ($_revision) {
214 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
215 }
216 push @log_args, "-r$_revision";
217 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
218
219 my $svn_log = svn_log_raw(@log_args);
220 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
221
222 my $base = shift @$svn_log or croak "No base revision!\n";
223 my $last_commit = undef;
224 unless (-d $SVN_WC) {
225 my @svn_co = ('svn','co',"-r$base->{revision}");
226 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
227 sys(@svn_co, $SVN_URL, $SVN_WC);
228 chdir $SVN_WC or croak $!;
229 $last_commit = git_commit($base, @parents);
230 assert_svn_wc_clean($base->{revision}, $last_commit);
231 } else {
232 chdir $SVN_WC or croak $!;
233 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
234 }
235 my @svn_up = qw(svn up);
236 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
237 my $last_rev = $base->{revision};
238 foreach my $log_msg (@$svn_log) {
239 assert_svn_wc_clean($last_rev, $last_commit);
240 $last_rev = $log_msg->{revision};
241 sys(@svn_up,"-r$last_rev");
242 $last_commit = git_commit($log_msg, $last_commit, @parents);
243 }
244 assert_svn_wc_clean($last_rev, $last_commit);
245 unless (-e "$GIT_DIR/refs/heads/master") {
246 sys(qw(git-update-ref refs/heads/master),$last_commit);
247 }
248 return pop @$svn_log;
249}
250
251sub commit {
252 my (@commits) = @_;
253 check_upgrade_needed();
254 if ($_stdin || !@commits) {
255 print "Reading from stdin...\n";
256 @commits = ();
257 while (<STDIN>) {
258 if (/\b($sha1_short)\b/o) {
259 unshift @commits, $1;
260 }
261 }
262 }
263 my @revs;
264 foreach my $c (@commits) {
265 chomp(my @tmp = safe_qx('git-rev-parse',$c));
266 if (scalar @tmp == 1) {
267 push @revs, $tmp[0];
268 } elsif (scalar @tmp > 1) {
269 push @revs, reverse (safe_qx('git-rev-list',@tmp));
270 } else {
271 die "Failed to rev-parse $c\n";
272 }
273 }
274 chomp @revs;
275
276 fetch();
277 chdir $SVN_WC or croak $!;
278 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
279 foreach my $c (@revs) {
280 my $mods = svn_checkout_tree($svn_current_rev, $c);
281 if (scalar @$mods == 0) {
282 print "Skipping, no changes detected\n";
283 next;
284 }
285 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
286 }
287 print "Done committing ",scalar @revs," revisions to SVN\n";
288
289}
290
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
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");
326 $SVN_UUID = svn_info($SVN_URL)->{'Repository UUID'} or
327 croak "Repository UUID unreadable\n";
328 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
329
330 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
331 print $fd '.svn',"\n";
332 close $fd or croak $!;
333 return $SVN_UUID;
334}
335
336sub assert_svn_wc_clean {
337 my ($svn_rev, $treeish) = @_;
338 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
339 croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
340 my $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 }
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";
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"
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') {
408 my $x = $mods[$#mods] or croak "Empty array\n";
409 if ($x->{chg} !~ /^(?:C|R)$/) {
410 croak "Error parsing $_, $x->{chg}\n";
411 }
412 $x->{file_a} = $_;
413 $state = 'file_b';
414 } elsif ($state eq 'file_b') {
415 my $x = $mods[$#mods] or croak "Empty array\n";
416 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
417 croak "Error parsing $_, $x->{chg}\n";
418 }
419 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
420 croak "Error parsing $_, $x->{chg}\n";
421 }
422 $x->{file_b} = $_;
423 $state = 'meta';
424 } else {
425 croak "Error parsing $_\n";
426 }
427 }
428 close $diff_fh or croak $!;
429
430 return \@mods;
431}
432
433sub svn_check_prop_executable {
434 my $m = shift;
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";
442 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
443 sys(qw(svn propdel svn:executable), $m->{file_b});
444 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
445 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
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
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
522sub svn_checkout_tree {
523 my ($svn_rev, $treeish) = @_;
524 my $from = file_to_s("$REV_DIR/$svn_rev");
525 assert_svn_wc_clean($svn_rev,$from);
526 print "diff-tree $from $treeish\n";
527 my $pid = open my $diff_fh, '-|';
528 defined $pid or croak $!;
529 if ($pid == 0) {
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;
533 exec(@diff_tree, $from, $treeish) or croak $!;
534 }
535 my $mods = parse_diff_tree($diff_fh);
536 unless (@$mods) {
537 # git can do empty commits, but SVN doesn't allow it...
538 return $mods;
539 }
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) {
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});
547 apply_mod_line_blob($m);
548 svn_check_prop_executable($m);
549 } elsif ($m->{chg} eq 'D') {
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});
554 apply_mod_line_blob($m);
555 svn_check_prop_executable($m);
556 } elsif ($m->{chg} eq 'M') {
557 apply_mod_line_blob($m);
558 svn_check_prop_executable($m);
559 } elsif ($m->{chg} eq 'T') {
560 sys(qw(svn rm --force),$m->{file_b});
561 apply_mod_line_blob($m);
562 sys(qw(svn add --force), $m->{file_b});
563 svn_check_prop_executable($m);
564 } elsif ($m->{chg} eq 'A') {
565 svn_ensure_parent_path( $m->{file_b} );
566 apply_mod_line_blob($m);
567 sys(qw(svn add --force), $m->{file_b});
568 svn_check_prop_executable($m);
569 } else {
570 croak "Invalid chg: $m->{chg}\n";
571 }
572 }
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);
616 }
617 }
618}
619
620sub svn_commit_tree {
621 my ($svn_rev, $commit) = @_;
622 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
623 my %log_msg = ( msg => '' );
624 open my $msg, '>', $commit_msg or croak $!;
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*$/);
638 } elsif (/^git-svn-id: /) {
639 # skip this, we regenerate the correct one
640 # on re-fetch anyways
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 }
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
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
670 my @svn_up = qw(svn up);
671 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
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";
694 sys(@svn_up);
695 return fetch("$rev_committed=$commit")->{revision};
696}
697
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;
708 my $state = 'sep';
709 while (<$log_fh>) {
710 chomp;
711 if (/^\-{72}$/) {
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 }
731 $state = 'rev';
732
733 # if we have an empty log message, put something there:
734 if (@svn_log) {
735 $svn_log[$#svn_log]->{msg} ||= "\n";
736 delete $svn_log[$#svn_log]->{lines};
737 }
738 next;
739 }
740 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
741 my $rev = $1;
742 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
743 ($lines) = ($lines =~ /(\d+)/);
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,
751 lines => $lines,
752 msg => '' );
753 if (defined $_authors && ! defined $users{$author}) {
754 die "Author: $author not defined in ",
755 "$_authors file\n";
756 }
757 push @svn_log, \%log_msg;
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') {
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 }
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 $_;
794 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
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 {
806 system( "git-diff-files --name-only -z ".
807 " | git-update-index --remove -z --stdin && ".
808 "git-ls-files -z --others ".
809 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
810 " | git-update-index --add -z --stdin"
811 ) == 0 or croak $?
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 $!;
856 $SVN_UUID ||= svn_info('.')->{'Repository UUID'};
857
858 map_tree_joins() if (@_branch_from && !%tree_map);
859
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 $?;
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 }
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}",
895 " $SVN_UUID\n" or croak $!;
896 $msg_fh->flush == 0 or croak $!;
897 seek $msg_fh, 0, 0 or croak $!;
898
899 set_commit_env($log_msg);
900
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 }
916 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
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
926sub set_commit_env {
927 my ($log_msg) = @_;
928 my $author = $log_msg->{author};
929 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
930 : ($author,"$author\@$SVN_UUID");
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
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
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;
949 if (-l $link || -f _) {
950 unlink $link or croak $!;
951 }
952
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;
961 if (-l $file || -f _) {
962 unlink $file or croak $!;
963 }
964
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}
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
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
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
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,
1080 chg => change type [MCRADT],
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;