contrib/git-svn: add --id/-i=$GIT_SVN_ID command-line switch
[git/jnareb-git.git] / contrib / git-svn / git-svn.perl
blobdb199a3648cfceb3956b5a8c7cf5d96e7f58040f
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $REV_DIR/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '0.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';
17 # If SVN:: library support is added, please make the dependencies
18 # optional and preserve the capability to use the command-line client.
19 # use eval { require SVN::... } to make it lazy load
20 # We don't use any modules not in the standard Perl distribution:
21 use Carp qw/croak/;
22 use IO::File qw//;
23 use File::Basename qw/dirname basename/;
24 use File::Path qw/mkpath/;
25 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
26 use File::Spec qw//;
27 use POSIX qw/strftime/;
28 my $sha1 = qr/[a-f\d]{40}/;
29 my $sha1_short = qr/[a-f\d]{4,40}/;
30 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
31 $_find_copies_harder, $_l, $_version, $_upgrade, $_authors);
32 my (@_branch_from, %tree_map, %users);
34 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
35 'branch|b=s' => \@_branch_from,
36 'authors-file|A=s' => \$_authors );
37 my %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 } ],
54 my $cmd;
55 for (my $i = 0; $i < @ARGV; $i++) {
56 if (defined $cmd{$ARGV[$i]}) {
57 $cmd = $ARGV[$i];
58 splice @ARGV, $i, 1;
59 last;
63 # we may be called as git-svn-(command), or git-svn(command).
64 foreach (keys %cmd) {
65 if (/git\-svn\-?($_)(?:\.\w+)?$/) {
66 $cmd = $1;
67 last;
71 my %opts;
72 %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
74 GetOptions(%opts, 'help|H|h' => \$_help,
75 'version|V' => \$_version,
76 'id|i=s' => \$GIT_SVN) or exit 1;
78 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
79 $GIT_SVN_INDEX = "$GIT_DIR/$GIT_SVN/index";
80 $ENV{GIT_DIR} ||= $GIT_DIR;
81 $SVN_URL = undef;
82 $REV_DIR = "$GIT_DIR/$GIT_SVN/revs";
83 $SVN_WC = "$GIT_DIR/$GIT_SVN/tree";
85 usage(0) if $_help;
86 version() if $_version;
87 usage(1) unless defined $cmd;
88 load_authors() if $_authors;
89 svn_check_ignore_externals();
90 $cmd{$cmd}->[0]->(@ARGV);
91 exit 0;
93 ####################### primary functions ######################
94 sub usage {
95 my $exit = shift || 0;
96 my $fd = $exit ? \*STDERR : \*STDOUT;
97 print $fd <<"";
98 git-svn - bidirectional operations between a single Subversion tree and git
99 Usage: $0 <command> [options] [arguments]\n
100 Available commands:
102 foreach (sort keys %cmd) {
103 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
105 print $fd <<"";
106 \nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
107 you're tracking multiple SVN branches/repositories in one git repository
108 and want to keep them separate. See git-svn(1) for more information.
110 exit $exit;
113 sub version {
114 print "git-svn version $VERSION\n";
115 exit 0;
118 sub rebuild {
119 $SVN_URL = shift or undef;
120 my $newest_rev = 0;
121 if ($_upgrade) {
122 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
123 } else {
124 check_upgrade_needed();
127 my $pid = open(my $rev_list,'-|');
128 defined $pid or croak $!;
129 if ($pid == 0) {
130 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
132 my $latest;
133 while (<$rev_list>) {
134 chomp;
135 my $c = $_;
136 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
137 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
138 next if (!@commit); # skip merges
139 my $id = $commit[$#commit];
140 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
141 \s([a-f\d\-]+)$/x);
142 if (!$rev || !$uuid || !$url) {
143 # some of the original repositories I made had
144 # indentifiers like this:
145 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
146 \@([a-f\d\-]+)/x);
147 if (!$rev || !$uuid) {
148 croak "Unable to extract revision or UUID from ",
149 "$c, $id\n";
153 # if we merged or otherwise started elsewhere, this is
154 # how we break out of it
155 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
156 next if (defined $SVN_URL && ($url ne $SVN_URL));
158 print "r$rev = $c\n";
159 unless (defined $latest) {
160 if (!$SVN_URL && !$url) {
161 croak "SVN repository location required: $url\n";
163 $SVN_URL ||= $url;
164 $SVN_UUID ||= setup_git_svn();
165 $latest = $rev;
167 assert_revision_eq_or_unknown($rev, $c);
168 sys('git-update-ref',"$GIT_SVN/revs/$rev",$c);
169 $newest_rev = $rev if ($rev > $newest_rev);
171 close $rev_list or croak $?;
172 if (!chdir $SVN_WC) {
173 my @svn_co = ('svn','co',"-r$latest");
174 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
175 sys(@svn_co, $SVN_URL, $SVN_WC);
176 chdir $SVN_WC or croak $!;
179 $pid = fork;
180 defined $pid or croak $!;
181 if ($pid == 0) {
182 my @svn_up = qw(svn up);
183 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
184 sys(@svn_up,"-r$newest_rev");
185 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
186 git_addremove();
187 exec('git-write-tree');
189 waitpid $pid, 0;
191 if ($_upgrade) {
192 print STDERR <<"";
193 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
194 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
199 sub init {
200 $SVN_URL = shift or croak "SVN repository location required\n";
201 unless (-d $GIT_DIR) {
202 sys('git-init-db');
204 setup_git_svn();
207 sub fetch {
208 my (@parents) = @_;
209 check_upgrade_needed();
210 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
211 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
212 unless ($_revision) {
213 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
215 push @log_args, "-r$_revision";
216 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
218 my $svn_log = svn_log_raw(@log_args);
219 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
221 my $base = shift @$svn_log or croak "No base revision!\n";
222 my $last_commit = undef;
223 unless (-d $SVN_WC) {
224 my @svn_co = ('svn','co',"-r$base->{revision}");
225 push @svn_co,'--ignore-externals' unless $_no_ignore_ext;
226 sys(@svn_co, $SVN_URL, $SVN_WC);
227 chdir $SVN_WC or croak $!;
228 $last_commit = git_commit($base, @parents);
229 assert_svn_wc_clean($base->{revision}, $last_commit);
230 } else {
231 chdir $SVN_WC or croak $!;
232 $last_commit = file_to_s("$REV_DIR/$base->{revision}");
234 my @svn_up = qw(svn up);
235 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
236 my $last_rev = $base->{revision};
237 foreach my $log_msg (@$svn_log) {
238 assert_svn_wc_clean($last_rev, $last_commit);
239 $last_rev = $log_msg->{revision};
240 sys(@svn_up,"-r$last_rev");
241 $last_commit = git_commit($log_msg, $last_commit, @parents);
243 assert_svn_wc_clean($last_rev, $last_commit);
244 unless (-e "$GIT_DIR/refs/heads/master") {
245 sys(qw(git-update-ref refs/heads/master),$last_commit);
247 return pop @$svn_log;
250 sub commit {
251 my (@commits) = @_;
252 check_upgrade_needed();
253 if ($_stdin || !@commits) {
254 print "Reading from stdin...\n";
255 @commits = ();
256 while (<STDIN>) {
257 if (/\b($sha1_short)\b/o) {
258 unshift @commits, $1;
262 my @revs;
263 foreach my $c (@commits) {
264 chomp(my @tmp = safe_qx('git-rev-parse',$c));
265 if (scalar @tmp == 1) {
266 push @revs, $tmp[0];
267 } elsif (scalar @tmp > 1) {
268 push @revs, reverse (safe_qx('git-rev-list',@tmp));
269 } else {
270 die "Failed to rev-parse $c\n";
273 chomp @revs;
275 fetch();
276 chdir $SVN_WC or croak $!;
277 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
278 foreach my $c (@revs) {
279 my $mods = svn_checkout_tree($svn_current_rev, $c);
280 if (scalar @$mods == 0) {
281 print "Skipping, no changes detected\n";
282 next;
284 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
286 print "Done committing ",scalar @revs," revisions to SVN\n";
290 sub show_ignore {
291 require File::Find or die $!;
292 my $exclude_file = "$GIT_DIR/info/exclude";
293 open my $fh, '<', $exclude_file or croak $!;
294 chomp(my @excludes = (<$fh>));
295 close $fh or croak $!;
297 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
298 chdir $SVN_WC or croak $!;
299 my %ign;
300 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
301 s#^\./##;
302 @{$ign{$_}} = safe_qx(qw(svn propget svn:ignore),$_);
303 }}, no_chdir=>1},'.');
305 print "\n# /\n";
306 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
307 delete $ign{'.'};
308 foreach my $i (sort keys %ign) {
309 print "\n# ",$i,"\n";
310 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
314 ########################### utility functions #########################
316 sub setup_git_svn {
317 defined $SVN_URL or croak "SVN repository location required\n";
318 unless (-d $GIT_DIR) {
319 croak "GIT_DIR=$GIT_DIR does not exist!\n";
321 mkpath(["$GIT_DIR/$GIT_SVN"]);
322 mkpath(["$GIT_DIR/$GIT_SVN/info"]);
323 mkpath([$REV_DIR]);
324 s_to_file($SVN_URL,"$GIT_DIR/$GIT_SVN/info/url");
325 $SVN_UUID = svn_info($SVN_URL)->{'Repository UUID'} or
326 croak "Repository UUID unreadable\n";
327 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
329 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
330 print $fd '.svn',"\n";
331 close $fd or croak $!;
332 return $SVN_UUID;
335 sub assert_svn_wc_clean {
336 my ($svn_rev, $treeish) = @_;
337 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
338 croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
339 my $svn_info = svn_info('.');
340 if ($svn_rev != $svn_info->{'Last Changed Rev'}) {
341 croak "Expected r$svn_rev, got r",
342 $svn_info->{'Last Changed Rev'},"\n";
344 my @status = grep(!/^Performing status on external/,(`svn status`));
345 @status = grep(!/^\s*$/,@status);
346 if (scalar @status) {
347 print STDERR "Tree ($SVN_WC) is not clean:\n";
348 print STDERR $_ foreach @status;
349 croak;
351 assert_tree($treeish);
354 sub assert_tree {
355 my ($treeish) = @_;
356 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
357 chomp(my $type = `git-cat-file -t $treeish`);
358 my $expected;
359 while ($type eq 'tag') {
360 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
362 if ($type eq 'commit') {
363 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
364 ($expected) = ($expected =~ /^tree ($sha1)$/);
365 die "Unable to get tree from $treeish\n" unless $expected;
366 } elsif ($type eq 'tree') {
367 $expected = $treeish;
368 } else {
369 die "$treeish is a $type, expected tree, tag or commit\n";
372 my $old_index = $ENV{GIT_INDEX_FILE};
373 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
374 if (-e $tmpindex) {
375 unlink $tmpindex or croak $!;
377 $ENV{GIT_INDEX_FILE} = $tmpindex;
378 git_addremove();
379 chomp(my $tree = `git-write-tree`);
380 if ($old_index) {
381 $ENV{GIT_INDEX_FILE} = $old_index;
382 } else {
383 delete $ENV{GIT_INDEX_FILE};
385 if ($tree ne $expected) {
386 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
390 sub parse_diff_tree {
391 my $diff_fh = shift;
392 local $/ = "\0";
393 my $state = 'meta';
394 my @mods;
395 while (<$diff_fh>) {
396 chomp $_; # this gets rid of the trailing "\0"
397 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
398 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
399 push @mods, { mode_a => $1, mode_b => $2,
400 sha1_b => $3, chg => $4 };
401 if ($4 =~ /^(?:C|R)$/) {
402 $state = 'file_a';
403 } else {
404 $state = 'file_b';
406 } elsif ($state eq 'file_a') {
407 my $x = $mods[$#mods] or croak "Empty array\n";
408 if ($x->{chg} !~ /^(?:C|R)$/) {
409 croak "Error parsing $_, $x->{chg}\n";
411 $x->{file_a} = $_;
412 $state = 'file_b';
413 } elsif ($state eq 'file_b') {
414 my $x = $mods[$#mods] or croak "Empty array\n";
415 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
416 croak "Error parsing $_, $x->{chg}\n";
418 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
419 croak "Error parsing $_, $x->{chg}\n";
421 $x->{file_b} = $_;
422 $state = 'meta';
423 } else {
424 croak "Error parsing $_\n";
427 close $diff_fh or croak $!;
429 return \@mods;
432 sub svn_check_prop_executable {
433 my $m = shift;
434 return if -l $m->{file_b};
435 if ($m->{mode_b} =~ /755$/) {
436 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
437 if ($m->{mode_a} !~ /755$/) {
438 sys(qw(svn propset svn:executable 1), $m->{file_b});
440 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
441 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
442 sys(qw(svn propdel svn:executable), $m->{file_b});
443 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
444 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
448 sub svn_ensure_parent_path {
449 my $dir_b = dirname(shift);
450 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
451 mkpath([$dir_b]) unless (-d $dir_b);
452 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
455 sub precommit_check {
456 my $mods = shift;
457 my (%rm_file, %rmdir_check, %added_check);
459 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
460 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
461 if ($m->{chg} eq 'R') {
462 if (-d $m->{file_b}) {
463 err_dir_to_file("$m->{file_a} => $m->{file_b}");
465 # dir/$file => dir/file/$file
466 my $dirname = dirname($m->{file_b});
467 while ($dirname ne File::Spec->curdir) {
468 if ($dirname ne $m->{file_a}) {
469 $dirname = dirname($dirname);
470 next;
472 err_file_to_dir("$m->{file_a} => $m->{file_b}");
474 # baz/zzz => baz (baz is a file)
475 $dirname = dirname($m->{file_a});
476 while ($dirname ne File::Spec->curdir) {
477 if ($dirname ne $m->{file_b}) {
478 $dirname = dirname($dirname);
479 next;
481 err_dir_to_file("$m->{file_a} => $m->{file_b}");
484 if ($m->{chg} =~ /^(D|R)$/) {
485 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
486 $rm_file{ $m->{$t} } = 1;
487 my $dirname = dirname( $m->{$t} );
488 my $basename = basename( $m->{$t} );
489 $rmdir_check{$dirname}->{$basename} = 1;
490 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
491 if (-d $m->{file_b}) {
492 err_dir_to_file($m->{file_b});
494 my $dirname = dirname( $m->{file_b} );
495 my $basename = basename( $m->{file_b} );
496 $added_check{$dirname}->{$basename} = 1;
497 while ($dirname ne File::Spec->curdir) {
498 if ($rm_file{$dirname}) {
499 err_file_to_dir($m->{file_b});
501 $dirname = dirname $dirname;
505 return (\%rmdir_check, \%added_check);
507 sub err_dir_to_file {
508 my $file = shift;
509 print STDERR "Node change from directory to file ",
510 "is not supported by Subversion: ",$file,"\n";
511 exit 1;
513 sub err_file_to_dir {
514 my $file = shift;
515 print STDERR "Node change from file to directory ",
516 "is not supported by Subversion: ",$file,"\n";
517 exit 1;
521 sub svn_checkout_tree {
522 my ($svn_rev, $treeish) = @_;
523 my $from = file_to_s("$REV_DIR/$svn_rev");
524 assert_svn_wc_clean($svn_rev,$from);
525 print "diff-tree $from $treeish\n";
526 my $pid = open my $diff_fh, '-|';
527 defined $pid or croak $!;
528 if ($pid == 0) {
529 my @diff_tree = qw(git-diff-tree -z -r -C);
530 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
531 push @diff_tree, "-l$_l" if defined $_l;
532 exec(@diff_tree, $from, $treeish) or croak $!;
534 my $mods = parse_diff_tree($diff_fh);
535 unless (@$mods) {
536 # git can do empty commits, but SVN doesn't allow it...
537 return $mods;
539 my ($rm, $add) = precommit_check($mods);
541 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
542 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
543 if ($m->{chg} eq 'C') {
544 svn_ensure_parent_path( $m->{file_b} );
545 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
546 apply_mod_line_blob($m);
547 svn_check_prop_executable($m);
548 } elsif ($m->{chg} eq 'D') {
549 sys(qw(svn rm --force), $m->{file_b});
550 } elsif ($m->{chg} eq 'R') {
551 svn_ensure_parent_path( $m->{file_b} );
552 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
553 apply_mod_line_blob($m);
554 svn_check_prop_executable($m);
555 } elsif ($m->{chg} eq 'M') {
556 apply_mod_line_blob($m);
557 svn_check_prop_executable($m);
558 } elsif ($m->{chg} eq 'T') {
559 sys(qw(svn rm --force),$m->{file_b});
560 apply_mod_line_blob($m);
561 sys(qw(svn add --force), $m->{file_b});
562 svn_check_prop_executable($m);
563 } elsif ($m->{chg} eq 'A') {
564 svn_ensure_parent_path( $m->{file_b} );
565 apply_mod_line_blob($m);
566 sys(qw(svn add --force), $m->{file_b});
567 svn_check_prop_executable($m);
568 } else {
569 croak "Invalid chg: $m->{chg}\n";
573 assert_tree($treeish);
574 if ($_rmdir) { # remove empty directories
575 handle_rmdir($rm, $add);
577 assert_tree($treeish);
578 return $mods;
581 # svn ls doesn't work with respect to the current working tree, but what's
582 # in the repository. There's not even an option for it... *sigh*
583 # (added files don't show up and removed files remain in the ls listing)
584 sub svn_ls_current {
585 my ($dir, $rm, $add) = @_;
586 chomp(my @ls = safe_qx('svn','ls',$dir));
587 my @ret = ();
588 foreach (@ls) {
589 s#/$##; # trailing slashes are evil
590 push @ret, $_ unless $rm->{$dir}->{$_};
592 if (exists $add->{$dir}) {
593 push @ret, keys %{$add->{$dir}};
595 return \@ret;
598 sub handle_rmdir {
599 my ($rm, $add) = @_;
601 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
602 my $ls = svn_ls_current($dir, $rm, $add);
603 next if (scalar @$ls);
604 sys(qw(svn rm --force),$dir);
606 my $dn = dirname $dir;
607 $rm->{ $dn }->{ basename $dir } = 1;
608 $ls = svn_ls_current($dn, $rm, $add);
609 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
610 sys(qw(svn rm --force),$dn);
611 $dir = basename $dn;
612 $dn = dirname $dn;
613 $rm->{ $dn }->{ $dir } = 1;
614 $ls = svn_ls_current($dn, $rm, $add);
619 sub svn_commit_tree {
620 my ($svn_rev, $commit) = @_;
621 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
622 my %log_msg = ( msg => '' );
623 open my $msg, '>', $commit_msg or croak $!;
625 chomp(my $type = `git-cat-file -t $commit`);
626 if ($type eq 'commit') {
627 my $pid = open my $msg_fh, '-|';
628 defined $pid or croak $!;
630 if ($pid == 0) {
631 exec(qw(git-cat-file commit), $commit) or croak $!;
633 my $in_msg = 0;
634 while (<$msg_fh>) {
635 if (!$in_msg) {
636 $in_msg = 1 if (/^\s*$/);
637 } elsif (/^git-svn-id: /) {
638 # skip this, we regenerate the correct one
639 # on re-fetch anyways
640 } else {
641 print $msg $_ or croak $!;
644 close $msg_fh or croak $!;
646 close $msg or croak $!;
648 if ($_edit || ($type eq 'tree')) {
649 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
650 system($editor, $commit_msg);
653 # file_to_s removes all trailing newlines, so just use chomp() here:
654 open $msg, '<', $commit_msg or croak $!;
655 { local $/; chomp($log_msg{msg} = <$msg>); }
656 close $msg or croak $!;
658 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
659 print "Committing $commit: $oneline\n";
661 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
662 my ($committed) = grep(/^Committed revision \d+\./,@ci_output);
663 unlink $commit_msg;
664 defined $committed or croak
665 "Commit output failed to parse committed revision!\n",
666 join("\n",@ci_output),"\n";
667 my ($rev_committed) = ($committed =~ /^Committed revision (\d+)\./);
669 my @svn_up = qw(svn up);
670 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
671 if ($rev_committed == ($svn_rev + 1)) {
672 push @svn_up, "-r$rev_committed";
673 sys(@svn_up);
674 my $info = svn_info('.');
675 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
676 if ($info->{'Last Changed Rev'} != $rev_committed) {
677 croak "$info->{'Last Changed Rev'} != $rev_committed\n"
679 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
680 /(\d{4})\-(\d\d)\-(\d\d)\s
681 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
682 or croak "Failed to parse date: $date\n";
683 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
684 $log_msg{author} = $info->{'Last Changed Author'};
685 $log_msg{revision} = $rev_committed;
686 $log_msg{msg} .= "\n";
687 my $parent = file_to_s("$REV_DIR/$svn_rev");
688 git_commit(\%log_msg, $parent, $commit);
689 return $rev_committed;
691 # resync immediately
692 push @svn_up, "-r$svn_rev";
693 sys(@svn_up);
694 return fetch("$rev_committed=$commit")->{revision};
697 sub svn_log_raw {
698 my (@log_args) = @_;
699 my $pid = open my $log_fh,'-|';
700 defined $pid or croak $!;
702 if ($pid == 0) {
703 exec (qw(svn log), @log_args) or croak $!
706 my @svn_log;
707 my $state = 'sep';
708 while (<$log_fh>) {
709 chomp;
710 if (/^\-{72}$/) {
711 if ($state eq 'msg') {
712 if ($svn_log[$#svn_log]->{lines}) {
713 $svn_log[$#svn_log]->{msg} .= $_."\n";
714 unless(--$svn_log[$#svn_log]->{lines}) {
715 $state = 'sep';
717 } else {
718 croak "Log parse error at: $_\n",
719 $svn_log[$#svn_log]->{revision},
720 "\n";
722 next;
724 if ($state ne 'sep') {
725 croak "Log parse error at: $_\n",
726 "state: $state\n",
727 $svn_log[$#svn_log]->{revision},
728 "\n";
730 $state = 'rev';
732 # if we have an empty log message, put something there:
733 if (@svn_log) {
734 $svn_log[$#svn_log]->{msg} ||= "\n";
735 delete $svn_log[$#svn_log]->{lines};
737 next;
739 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
740 my $rev = $1;
741 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
742 ($lines) = ($lines =~ /(\d+)/);
743 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
744 /(\d{4})\-(\d\d)\-(\d\d)\s
745 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
746 or croak "Failed to parse date: $date\n";
747 my %log_msg = ( revision => $rev,
748 date => "$tz $Y-$m-$d $H:$M:$S",
749 author => $author,
750 lines => $lines,
751 msg => '' );
752 if (defined $_authors && ! defined $users{$author}) {
753 die "Author: $author not defined in ",
754 "$_authors file\n";
756 push @svn_log, \%log_msg;
757 $state = 'msg_start';
758 next;
760 # skip the first blank line of the message:
761 if ($state eq 'msg_start' && /^$/) {
762 $state = 'msg';
763 } elsif ($state eq 'msg') {
764 if ($svn_log[$#svn_log]->{lines}) {
765 $svn_log[$#svn_log]->{msg} .= $_."\n";
766 unless (--$svn_log[$#svn_log]->{lines}) {
767 $state = 'sep';
769 } else {
770 croak "Log parse error at: $_\n",
771 $svn_log[$#svn_log]->{revision},"\n";
775 close $log_fh or croak $?;
776 return \@svn_log;
779 sub svn_info {
780 my $url = shift || $SVN_URL;
782 my $pid = open my $info_fh, '-|';
783 defined $pid or croak $!;
785 if ($pid == 0) {
786 exec(qw(svn info),$url) or croak $!;
789 my $ret = {};
790 # only single-lines seem to exist in svn info output
791 while (<$info_fh>) {
792 chomp $_;
793 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
794 $ret->{$1} = $2;
795 push @{$ret->{-order}}, $1;
798 close $info_fh or croak $!;
799 return $ret;
802 sub sys { system(@_) == 0 or croak $? }
804 sub git_addremove {
805 system( "git-diff-files --name-only -z ".
806 " | git-update-index --remove -z --stdin && ".
807 "git-ls-files -z --others ".
808 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
809 " | git-update-index --add -z --stdin"
810 ) == 0 or croak $?
813 sub s_to_file {
814 my ($str, $file, $mode) = @_;
815 open my $fd,'>',$file or croak $!;
816 print $fd $str,"\n" or croak $!;
817 close $fd or croak $!;
818 chmod ($mode &~ umask, $file) if (defined $mode);
821 sub file_to_s {
822 my $file = shift;
823 open my $fd,'<',$file or croak "$!: file: $file\n";
824 local $/;
825 my $ret = <$fd>;
826 close $fd or croak $!;
827 $ret =~ s/\s*$//s;
828 return $ret;
831 sub assert_revision_unknown {
832 my $revno = shift;
833 if (-f "$REV_DIR/$revno") {
834 croak "$REV_DIR/$revno already exists! ",
835 "Why are we refetching it?";
839 sub assert_revision_eq_or_unknown {
840 my ($revno, $commit) = @_;
841 if (-f "$REV_DIR/$revno") {
842 my $current = file_to_s("$REV_DIR/$revno");
843 if ($commit ne $current) {
844 croak "$REV_DIR/$revno already exists!\n",
845 "current: $current\nexpected: $commit\n";
847 return;
851 sub git_commit {
852 my ($log_msg, @parents) = @_;
853 assert_revision_unknown($log_msg->{revision});
854 my $out_fh = IO::File->new_tmpfile or croak $!;
855 $SVN_UUID ||= svn_info('.')->{'Repository UUID'};
857 map_tree_joins() if (@_branch_from && !%tree_map);
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;
868 } else {
869 push @exec_parents, $p if $p =~ /$sha1_short/o;
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;
887 push @exec_parents, $_;
888 $seen_parent{$_} = 1;
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 " $SVN_UUID\n" or croak $!;
895 $msg_fh->flush == 0 or croak $!;
896 seek $msg_fh, 0, 0 or croak $!;
898 set_commit_env($log_msg);
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 $!;
906 waitpid($pid,0);
907 croak if $?;
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";
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;
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;
925 sub set_commit_env {
926 my ($log_msg) = @_;
927 my $author = $log_msg->{author};
928 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
929 : ($author,"$author\@$SVN_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};
935 sub 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});
944 sub 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 $!;
952 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
953 symlink $dest, $link or croak $!;
956 sub 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 $!;
964 open my $blob_fh, '>', $file or croak "$!: $file\n";
965 my $pid = fork;
966 defined $pid or croak $!;
968 if ($pid == 0) {
969 open STDOUT, '>&', $blob_fh or croak $!;
970 exec('git-cat-file','blob',$blob);
972 waitpid $pid, 0;
973 croak $? if $?;
975 close $blob_fh or croak $!;
978 sub safe_qx {
979 my $pid = open my $child, '-|';
980 defined $pid or croak $!;
981 if ($pid == 0) {
982 exec(@_) or croak $?;
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);
990 sub 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;
999 sub 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 $?;
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);
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;
1020 # fills %tree_map with a reverse mapping of trees to commits. Useful
1021 # for finding parents to commit on.
1022 sub 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 $?;
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";
1036 push @{$tree_map{$tree}}, $commit;
1039 close $pipe or croak $?;
1043 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1044 sub 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];
1052 close $authors or croak $!;
1055 __END__
1057 Data structures:
1059 @svn_log = array of log_msg hashes
1061 $log_msg hash
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'
1071 @mods = array of diff-index line hashes, each element represents one line
1072 of diff-index output
1074 diff-index line ($m hash)
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)