]> git.ipfire.org Git - thirdparty/git.git/blame - contrib/git-svn/git-svn.perl
contrib/git-svn: add --id/-i=$GIT_SVN_ID command-line switch
[thirdparty/git.git] / contrib / git-svn / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
1ca72aef 7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
3397f9df
EW
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $REV_DIR/;
10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
3c0b7511 11$VERSION = '0.10.0';
3397f9df 12$GIT_DIR = $ENV{GIT_DIR} || "$ENV{PWD}/.git";
3397f9df
EW
13# make sure the svn binary gives consistent output between locales and TZs:
14$ENV{TZ} = 'UTC';
15$ENV{LC_ALL} = 'C';
16
17# If SVN:: library support is added, please make the dependencies
18# optional and preserve the capability to use the command-line client.
ce6f3519 19# use eval { require SVN::... } to make it lazy load
eeb0abe0 20# We don't use any modules not in the standard Perl distribution:
3397f9df
EW
21use Carp qw/croak/;
22use IO::File qw//;
23use File::Basename qw/dirname basename/;
24use File::Path qw/mkpath/;
25use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
26use File::Spec qw//;
e17512f3 27use POSIX qw/strftime/;
3397f9df 28my $sha1 = qr/[a-f\d]{40}/;
ac8e0b91 29my $sha1_short = qr/[a-f\d]{4,40}/;
72942938 30my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
a9612be2
EW
31 $_find_copies_harder, $_l, $_version, $_upgrade, $_authors);
32my (@_branch_from, %tree_map, %users);
3397f9df 33
eeb0abe0 34my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
69f0d91e 35 'branch|b=s' => \@_branch_from,
eeb0abe0 36 'authors-file|A=s' => \$_authors );
3397f9df 37my %cmd = (
eeb0abe0
EW
38 fetch => [ \&fetch, "Download new revisions from SVN",
39 { 'revision|r=s' => \$_revision, %fc_opts } ],
40 init => [ \&init, "Initialize and fetch (import)", { } ],
41 commit => [ \&commit, "Commit git revisions to SVN",
42 { 'stdin|' => \$_stdin,
43 'edit|e' => \$_edit,
44 'rmdir' => \$_rmdir,
45 'find-copies-harder' => \$_find_copies_harder,
46 'l=i' => \$_l,
47 %fc_opts,
48 } ],
49 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
50 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
51 { 'no-ignore-externals' => \$_no_ignore_ext,
52 'upgrade' => \$_upgrade } ],
3397f9df
EW
53);
54my $cmd;
55for (my $i = 0; $i < @ARGV; $i++) {
56 if (defined $cmd{$ARGV[$i]}) {
57 $cmd = $ARGV[$i];
58 splice @ARGV, $i, 1;
59 last;
60 }
61};
62
63# we may be called as git-svn-(command), or git-svn(command).
64foreach (keys %cmd) {
65 if (/git\-svn\-?($_)(?:\.\w+)?$/) {
66 $cmd = $1;
67 last;
68 }
69}
a9612be2 70
eeb0abe0
EW
71my %opts;
72%opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 73
6f0783cf
EW
74GetOptions(%opts, 'help|H|h' => \$_help,
75 'version|V' => \$_version,
76 'id|i=s' => \$GIT_SVN) or exit 1;
77
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";
84
3397f9df 85usage(0) if $_help;
551ce28f 86version() if $_version;
eeb0abe0
EW
87usage(1) unless defined $cmd;
88load_authors() if $_authors;
3397f9df
EW
89svn_check_ignore_externals();
90$cmd{$cmd}->[0]->(@ARGV);
91exit 0;
92
93####################### primary functions ######################
94sub usage {
95 my $exit = shift || 0;
96 my $fd = $exit ? \*STDERR : \*STDOUT;
97 print $fd <<"";
98git-svn - bidirectional operations between a single Subversion tree and git
99Usage: $0 <command> [options] [arguments]\n
100Available commands:
101
102 foreach (sort keys %cmd) {
ac8e0b91 103 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
3397f9df
EW
104 }
105 print $fd <<"";
106\nGIT_SVN_ID may be set in the environment to an arbitrary identifier if
107you're tracking multiple SVN branches/repositories in one git repository
ac8e0b91 108and want to keep them separate. See git-svn(1) for more information.
3397f9df
EW
109
110 exit $exit;
111}
112
551ce28f
EW
113sub version {
114 print "git-svn version $VERSION\n";
115 exit 0;
116}
117
3397f9df
EW
118sub rebuild {
119 $SVN_URL = shift or undef;
3397f9df 120 my $newest_rev = 0;
2beb3cdd
EW
121 if ($_upgrade) {
122 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
123 } else {
124 check_upgrade_needed();
125 }
3397f9df
EW
126
127 my $pid = open(my $rev_list,'-|');
128 defined $pid or croak $!;
129 if ($pid == 0) {
2beb3cdd 130 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
3397f9df 131 }
2beb3cdd 132 my $latest;
3397f9df
EW
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";
150 }
151 }
2beb3cdd
EW
152
153 # if we merged or otherwise started elsewhere, this is
154 # how we break out of it
1ca72aef 155 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
2beb3cdd
EW
156 next if (defined $SVN_URL && ($url ne $SVN_URL));
157
3397f9df 158 print "r$rev = $c\n";
2beb3cdd 159 unless (defined $latest) {
3397f9df
EW
160 if (!$SVN_URL && !$url) {
161 croak "SVN repository location required: $url\n";
162 }
163 $SVN_URL ||= $url;
1ca72aef 164 $SVN_UUID ||= setup_git_svn();
2beb3cdd 165 $latest = $rev;
3397f9df
EW
166 }
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);
170 }
171 close $rev_list or croak $?;
172 if (!chdir $SVN_WC) {
2beb3cdd 173 my @svn_co = ('svn','co',"-r$latest");
3397f9df
EW
174 push @svn_co, '--ignore-externals' unless $_no_ignore_ext;
175 sys(@svn_co, $SVN_URL, $SVN_WC);
176 chdir $SVN_WC or croak $!;
177 }
178
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');
188 }
189 waitpid $pid, 0;
2beb3cdd
EW
190
191 if ($_upgrade) {
192 print STDERR <<"";
193Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
194when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
195
196 }
3397f9df
EW
197}
198
199sub init {
200 $SVN_URL = shift or croak "SVN repository location required\n";
201 unless (-d $GIT_DIR) {
202 sys('git-init-db');
203 }
204 setup_git_svn();
205}
206
207sub fetch {
208 my (@parents) = @_;
2beb3cdd 209 check_upgrade_needed();
3397f9df
EW
210 $SVN_URL ||= file_to_s("$GIT_DIR/$GIT_SVN/info/url");
211 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
defc6492
EW
212 unless ($_revision) {
213 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
3397f9df 214 }
defc6492 215 push @log_args, "-r$_revision";
3397f9df
EW
216 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
217
ce6f3519 218 my $svn_log = svn_log_raw(@log_args);
defc6492 219 @$svn_log = sort { $a->{revision} <=> $b->{revision} } @$svn_log;
3397f9df
EW
220
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);
3397f9df
EW
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}");
233 }
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);
242 }
243 assert_svn_wc_clean($last_rev, $last_commit);
7f60b228
EW
244 unless (-e "$GIT_DIR/refs/heads/master") {
245 sys(qw(git-update-ref refs/heads/master),$last_commit);
246 }
3397f9df
EW
247 return pop @$svn_log;
248}
249
250sub commit {
251 my (@commits) = @_;
2beb3cdd 252 check_upgrade_needed();
3397f9df
EW
253 if ($_stdin || !@commits) {
254 print "Reading from stdin...\n";
255 @commits = ();
256 while (<STDIN>) {
1ca72aef 257 if (/\b($sha1_short)\b/o) {
3397f9df
EW
258 unshift @commits, $1;
259 }
260 }
261 }
262 my @revs;
8de010ad
EW
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";
271 }
3397f9df
EW
272 }
273 chomp @revs;
274
275 fetch();
276 chdir $SVN_WC or croak $!;
277 my $svn_current_rev = svn_info('.')->{'Last Changed Rev'};
278 foreach my $c (@revs) {
cf52b8f0
EW
279 my $mods = svn_checkout_tree($svn_current_rev, $c);
280 if (scalar @$mods == 0) {
281 print "Skipping, no changes detected\n";
282 next;
283 }
3397f9df
EW
284 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
285 }
286 print "Done committing ",scalar @revs," revisions to SVN\n";
287
288}
289
8f22562c
EW
290sub 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 $!;
296
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},'.');
304
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/ }
311 }
312}
313
3397f9df
EW
314########################### utility functions #########################
315
316sub 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";
320 }
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");
1ca72aef 325 $SVN_UUID = svn_info($SVN_URL)->{'Repository UUID'} or
3397f9df 326 croak "Repository UUID unreadable\n";
1ca72aef 327 s_to_file($SVN_UUID,"$GIT_DIR/$GIT_SVN/info/uuid");
3397f9df
EW
328
329 open my $fd, '>>', "$GIT_DIR/$GIT_SVN/info/exclude" or croak $!;
330 print $fd '.svn',"\n";
331 close $fd or croak $!;
1ca72aef 332 return $SVN_UUID;
3397f9df
EW
333}
334
335sub assert_svn_wc_clean {
cf52b8f0 336 my ($svn_rev, $treeish) = @_;
3397f9df 337 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
cf52b8f0 338 croak "$treeish is not a sha1!\n" unless ($treeish =~ /^$sha1$/o);
3397f9df
EW
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";
343 }
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;
350 }
cf52b8f0
EW
351 assert_tree($treeish);
352}
353
354sub 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`);
361 }
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";
370 }
371
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 $!;
376 }
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};
384 }
385 if ($tree ne $expected) {
386 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
3397f9df
EW
387 }
388}
389
390sub 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"
3397f9df
EW
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';
405 }
406 } elsif ($state eq 'file_a') {
cf52b8f0 407 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 408 if ($x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 409 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
410 }
411 $x->{file_a} = $_;
412 $state = 'file_b';
413 } elsif ($state eq 'file_b') {
cf52b8f0 414 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 415 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 416 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
417 }
418 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
cf52b8f0 419 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
420 }
421 $x->{file_b} = $_;
422 $state = 'meta';
423 } else {
cf52b8f0 424 croak "Error parsing $_\n";
3397f9df
EW
425 }
426 }
427 close $diff_fh or croak $!;
cf52b8f0 428
3397f9df
EW
429 return \@mods;
430}
431
432sub svn_check_prop_executable {
433 my $m = shift;
cf52b8f0
EW
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});
439 }
440 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
3397f9df
EW
441 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
442 sys(qw(svn propdel svn:executable), $m->{file_b});
cf52b8f0
EW
443 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
444 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
3397f9df
EW
445 }
446}
447
448sub 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");
453}
454
cf52b8f0
EW
455sub precommit_check {
456 my $mods = shift;
457 my (%rm_file, %rmdir_check, %added_check);
458
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}");
464 }
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;
471 }
472 err_file_to_dir("$m->{file_a} => $m->{file_b}");
473 }
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;
480 }
481 err_dir_to_file("$m->{file_a} => $m->{file_b}");
482 }
483 }
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});
493 }
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});
500 }
501 $dirname = dirname $dirname;
502 }
503 }
504 }
505 return (\%rmdir_check, \%added_check);
506
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;
512 }
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;
518 }
519}
520
3397f9df 521sub svn_checkout_tree {
cf52b8f0 522 my ($svn_rev, $treeish) = @_;
3397f9df
EW
523 my $from = file_to_s("$REV_DIR/$svn_rev");
524 assert_svn_wc_clean($svn_rev,$from);
ac8e0b91 525 print "diff-tree $from $treeish\n";
3397f9df
EW
526 my $pid = open my $diff_fh, '-|';
527 defined $pid or croak $!;
528 if ($pid == 0) {
72942938
EW
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;
cf52b8f0 532 exec(@diff_tree, $from, $treeish) or croak $!;
3397f9df
EW
533 }
534 my $mods = parse_diff_tree($diff_fh);
535 unless (@$mods) {
ac8e0b91 536 # git can do empty commits, but SVN doesn't allow it...
cf52b8f0 537 return $mods;
3397f9df 538 }
cf52b8f0
EW
539 my ($rm, $add) = precommit_check($mods);
540
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) {
3397f9df
EW
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});
cf52b8f0 546 apply_mod_line_blob($m);
3397f9df
EW
547 svn_check_prop_executable($m);
548 } elsif ($m->{chg} eq 'D') {
3397f9df
EW
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});
cf52b8f0 553 apply_mod_line_blob($m);
3397f9df 554 svn_check_prop_executable($m);
3397f9df 555 } elsif ($m->{chg} eq 'M') {
cf52b8f0 556 apply_mod_line_blob($m);
3397f9df
EW
557 svn_check_prop_executable($m);
558 } elsif ($m->{chg} eq 'T') {
559 sys(qw(svn rm --force),$m->{file_b});
cf52b8f0 560 apply_mod_line_blob($m);
3397f9df 561 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 562 svn_check_prop_executable($m);
3397f9df
EW
563 } elsif ($m->{chg} eq 'A') {
564 svn_ensure_parent_path( $m->{file_b} );
cf52b8f0 565 apply_mod_line_blob($m);
3397f9df 566 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 567 svn_check_prop_executable($m);
3397f9df
EW
568 } else {
569 croak "Invalid chg: $m->{chg}\n";
570 }
571 }
cf52b8f0
EW
572
573 assert_tree($treeish);
574 if ($_rmdir) { # remove empty directories
575 handle_rmdir($rm, $add);
576 }
577 assert_tree($treeish);
578 return $mods;
579}
580
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)
584sub 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}->{$_};
591 }
592 if (exists $add->{$dir}) {
593 push @ret, keys %{$add->{$dir}};
594 }
595 return \@ret;
596}
597
598sub handle_rmdir {
599 my ($rm, $add) = @_;
600
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);
605
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);
3397f9df
EW
615 }
616 }
617}
618
619sub svn_commit_tree {
620 my ($svn_rev, $commit) = @_;
621 my $commit_msg = "$GIT_DIR/$GIT_SVN/.svn-commit.tmp.$$";
e17512f3 622 my %log_msg = ( msg => '' );
ac8e0b91 623 open my $msg, '>', $commit_msg or croak $!;
3397f9df
EW
624
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 $!;
629
630 if ($pid == 0) {
631 exec(qw(git-cat-file commit), $commit) or croak $!;
632 }
633 my $in_msg = 0;
634 while (<$msg_fh>) {
635 if (!$in_msg) {
636 $in_msg = 1 if (/^\s*$/);
df746c5a
EW
637 } elsif (/^git-svn-id: /) {
638 # skip this, we regenerate the correct one
639 # on re-fetch anyways
3397f9df
EW
640 } else {
641 print $msg $_ or croak $!;
642 }
643 }
644 close $msg_fh or croak $!;
645 }
646 close $msg or croak $!;
647
648 if ($_edit || ($type eq 'tree')) {
649 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
650 system($editor, $commit_msg);
651 }
ac8e0b91
EW
652
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 $!;
657
658 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
659 print "Committing $commit: $oneline\n";
660
3397f9df
EW
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+)\./);
668
e17512f3 669 my @svn_up = qw(svn up);
3397f9df 670 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
e17512f3
EW
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"
678 }
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;
690 }
691 # resync immediately
692 push @svn_up, "-r$svn_rev";
3397f9df
EW
693 sys(@svn_up);
694 return fetch("$rev_committed=$commit")->{revision};
695}
696
3397f9df
EW
697sub svn_log_raw {
698 my (@log_args) = @_;
699 my $pid = open my $log_fh,'-|';
700 defined $pid or croak $!;
701
702 if ($pid == 0) {
703 exec (qw(svn log), @log_args) or croak $!
704 }
705
706 my @svn_log;
ce6f3519 707 my $state = 'sep';
3397f9df
EW
708 while (<$log_fh>) {
709 chomp;
710 if (/^\-{72}$/) {
ce6f3519
EW
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';
716 }
717 } else {
718 croak "Log parse error at: $_\n",
719 $svn_log[$#svn_log]->{revision},
720 "\n";
721 }
722 next;
723 }
724 if ($state ne 'sep') {
725 croak "Log parse error at: $_\n",
726 "state: $state\n",
727 $svn_log[$#svn_log]->{revision},
728 "\n";
729 }
3397f9df
EW
730 $state = 'rev';
731
732 # if we have an empty log message, put something there:
733 if (@svn_log) {
1c6bbbf3 734 $svn_log[$#svn_log]->{msg} ||= "\n";
ce6f3519 735 delete $svn_log[$#svn_log]->{lines};
3397f9df
EW
736 }
737 next;
738 }
739 if ($state eq 'rev' && s/^r(\d+)\s*\|\s*//) {
740 my $rev = $1;
ce6f3519
EW
741 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
742 ($lines) = ($lines =~ /(\d+)/);
3397f9df
EW
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,
ce6f3519 750 lines => $lines,
3397f9df 751 msg => '' );
a9612be2
EW
752 if (defined $_authors && ! defined $users{$author}) {
753 die "Author: $author not defined in ",
754 "$_authors file\n";
755 }
1c6bbbf3 756 push @svn_log, \%log_msg;
3397f9df
EW
757 $state = 'msg_start';
758 next;
759 }
760 # skip the first blank line of the message:
761 if ($state eq 'msg_start' && /^$/) {
762 $state = 'msg';
763 } elsif ($state eq 'msg') {
ce6f3519
EW
764 if ($svn_log[$#svn_log]->{lines}) {
765 $svn_log[$#svn_log]->{msg} .= $_."\n";
766 unless (--$svn_log[$#svn_log]->{lines}) {
767 $state = 'sep';
768 }
769 } else {
770 croak "Log parse error at: $_\n",
771 $svn_log[$#svn_log]->{revision},"\n";
772 }
3397f9df
EW
773 }
774 }
775 close $log_fh or croak $?;
776 return \@svn_log;
777}
778
779sub svn_info {
780 my $url = shift || $SVN_URL;
781
782 my $pid = open my $info_fh, '-|';
783 defined $pid or croak $!;
784
785 if ($pid == 0) {
786 exec(qw(svn info),$url) or croak $!;
787 }
788
789 my $ret = {};
790 # only single-lines seem to exist in svn info output
791 while (<$info_fh>) {
792 chomp $_;
e17512f3 793 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
3397f9df
EW
794 $ret->{$1} = $2;
795 push @{$ret->{-order}}, $1;
796 }
797 }
798 close $info_fh or croak $!;
799 return $ret;
800}
801
802sub sys { system(@_) == 0 or croak $? }
803
804sub git_addremove {
08703215 805 system( "git-diff-files --name-only -z ".
472ee9e3 806 " | git-update-index --remove -z --stdin && ".
08703215 807 "git-ls-files -z --others ".
3397f9df 808 "'--exclude-from=$GIT_DIR/$GIT_SVN/info/exclude'".
472ee9e3 809 " | git-update-index --add -z --stdin"
08703215 810 ) == 0 or croak $?
3397f9df
EW
811}
812
813sub 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);
819}
820
821sub 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;
829}
830
831sub 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?";
836 }
837}
838
839sub 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";
846 }
847 return;
848 }
849}
850
851sub git_commit {
852 my ($log_msg, @parents) = @_;
853 assert_revision_unknown($log_msg->{revision});
854 my $out_fh = IO::File->new_tmpfile or croak $!;
1ca72aef 855 $SVN_UUID ||= svn_info('.')->{'Repository UUID'};
3397f9df 856
69f0d91e
EW
857 map_tree_joins() if (@_branch_from && !%tree_map);
858
3397f9df
EW
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 $?;
69f0d91e
EW
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 }
3397f9df
EW
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}",
1ca72aef 894 " $SVN_UUID\n" or croak $!;
3397f9df
EW
895 $msg_fh->flush == 0 or croak $!;
896 seek $msg_fh, 0, 0 or croak $!;
897
1ca72aef 898 set_commit_env($log_msg);
a9612be2 899
3397f9df
EW
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 }
2beb3cdd 915 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
3397f9df
EW
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
a9612be2 925sub set_commit_env {
1ca72aef 926 my ($log_msg) = @_;
a9612be2
EW
927 my $author = $log_msg->{author};
928 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1ca72aef 929 : ($author,"$author\@$SVN_UUID");
a9612be2
EW
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
cf52b8f0
EW
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
3397f9df
EW
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;
cf52b8f0
EW
948 if (-l $link || -f _) {
949 unlink $link or croak $!;
950 }
951
3397f9df
EW
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;
cf52b8f0
EW
960 if (-l $file || -f _) {
961 unlink $file or croak $!;
962 }
963
3397f9df
EW
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}
2beb3cdd
EW
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
69f0d91e
EW
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
eeb0abe0
EW
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
3397f9df
EW
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,
ac8e0b91 1079 chg => change type [MCRADT],
3397f9df
EW
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;