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