]> git.ipfire.org Git - thirdparty/git.git/blame - contrib/git-svn/git-svn.perl
git-svn: Move all git-svn-related paths into $GIT_DIR/svn
[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 8 $GIT_SVN_INDEX $GIT_SVN
883d0a78 9 $GIT_DIR $REV_DIR $GIT_SVN_DIR/;
3397f9df 10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
304dac15 11$VERSION = '1.1.0-pre';
13ccd6d4
EW
12
13use Cwd qw/abs_path/;
14$GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15$ENV{GIT_DIR} = $GIT_DIR;
16
ce475dfc 17my $LC_ALL = $ENV{LC_ALL};
3397f9df
EW
18# make sure the svn binary gives consistent output between locales and TZs:
19$ENV{TZ} = 'UTC';
20$ENV{LC_ALL} = 'C';
21
22# If SVN:: library support is added, please make the dependencies
23# optional and preserve the capability to use the command-line client.
ce6f3519 24# use eval { require SVN::... } to make it lazy load
eeb0abe0 25# We don't use any modules not in the standard Perl distribution:
3397f9df
EW
26use Carp qw/croak/;
27use IO::File qw//;
28use File::Basename qw/dirname basename/;
29use File::Path qw/mkpath/;
30use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
31use File::Spec qw//;
e17512f3 32use POSIX qw/strftime/;
3397f9df 33my $sha1 = qr/[a-f\d]{40}/;
ac8e0b91 34my $sha1_short = qr/[a-f\d]{4,40}/;
72942938 35my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
162f4129 36 $_find_copies_harder, $_l, $_cp_similarity,
bf78b1d8 37 $_version, $_upgrade, $_authors, $_branch_all_refs);
a9612be2 38my (@_branch_from, %tree_map, %users);
8a97e368 39my ($_svn_co_url_revs, $_svn_pg_peg_revs);
883d0a78 40my @repo_path_split_cache;
3397f9df 41
eeb0abe0 42my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
69f0d91e 43 'branch|b=s' => \@_branch_from,
bf78b1d8 44 'branch-all-refs|B' => \$_branch_all_refs,
eeb0abe0 45 'authors-file|A=s' => \$_authors );
36f5b1f0
EW
46
47# yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
48my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
49
3397f9df 50my %cmd = (
eeb0abe0
EW
51 fetch => [ \&fetch, "Download new revisions from SVN",
52 { 'revision|r=s' => \$_revision, %fc_opts } ],
81c5a0e6
EW
53 init => [ \&init, "Initialize a repo for tracking" .
54 " (requires URL argument)", { } ],
eeb0abe0
EW
55 commit => [ \&commit, "Commit git revisions to SVN",
56 { 'stdin|' => \$_stdin,
57 'edit|e' => \$_edit,
58 'rmdir' => \$_rmdir,
59 'find-copies-harder' => \$_find_copies_harder,
60 'l=i' => \$_l,
162f4129 61 'copy-similarity|C=i'=> \$_cp_similarity,
eeb0abe0
EW
62 %fc_opts,
63 } ],
64 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings", { } ],
65 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
66 { 'no-ignore-externals' => \$_no_ignore_ext,
67 'upgrade' => \$_upgrade } ],
3397f9df
EW
68);
69my $cmd;
70for (my $i = 0; $i < @ARGV; $i++) {
71 if (defined $cmd{$ARGV[$i]}) {
72 $cmd = $ARGV[$i];
73 splice @ARGV, $i, 1;
74 last;
75 }
76};
77
448c81b4 78my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 79
53909056
EW
80# convert GetOpt::Long specs for use by git-repo-config
81foreach my $o (keys %opts) {
82 my $v = $opts{$o};
83 my ($key) = ($o =~ /^([a-z\-]+)/);
84 $key =~ s/-//g;
85 my $arg = 'git-repo-config';
86 $arg .= ' --int' if ($o =~ /=i$/);
87 $arg .= ' --bool' if ($o !~ /=[sfi]$/);
53909056 88 if (ref $v eq 'ARRAY') {
fc9957b0 89 chomp(my @tmp = `$arg --get-all svn.$key`);
5941a9e9 90 @$v = @tmp if @tmp;
53909056 91 } else {
fc9957b0 92 chomp(my $tmp = `$arg --get svn.$key`);
5941a9e9
EW
93 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
94 $$v = $tmp;
95 }
53909056
EW
96 }
97}
98
6f0783cf
EW
99GetOptions(%opts, 'help|H|h' => \$_help,
100 'version|V' => \$_version,
101 'id|i=s' => \$GIT_SVN) or exit 1;
102
103$GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
883d0a78
EW
104$GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
105$GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
6f0783cf 106$SVN_URL = undef;
883d0a78
EW
107$REV_DIR = "$GIT_SVN_DIR/revs";
108$SVN_WC = "$GIT_SVN_DIR/tree";
6f0783cf 109
3397f9df 110usage(0) if $_help;
551ce28f 111version() if $_version;
eeb0abe0
EW
112usage(1) unless defined $cmd;
113load_authors() if $_authors;
bf78b1d8 114load_all_refs() if $_branch_all_refs;
1d52aba8 115svn_compat_check();
883d0a78 116migration_check() unless $cmd eq 'init';
3397f9df
EW
117$cmd{$cmd}->[0]->(@ARGV);
118exit 0;
119
120####################### primary functions ######################
121sub usage {
122 my $exit = shift || 0;
123 my $fd = $exit ? \*STDERR : \*STDOUT;
124 print $fd <<"";
125git-svn - bidirectional operations between a single Subversion tree and git
126Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
127
128 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
129
130 foreach (sort keys %cmd) {
448c81b4 131 next if $cmd && $cmd ne $_;
ac8e0b91 132 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
133 foreach (keys %{$cmd{$_}->[2]}) {
134 # prints out arguments as they should be passed:
135 my $x = s#=s$## ? '<arg>' : s#=i$## ? '<num>' : '';
136 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
137 "--$_" : "-$_" }
138 split /\|/,$_)," $x\n";
139 }
3397f9df
EW
140 }
141 print $fd <<"";
448c81b4
EW
142\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
143arbitrary identifier if you're tracking multiple SVN branches/repositories in
144one git repository and want to keep them separate. See git-svn(1) for more
145information.
3397f9df
EW
146
147 exit $exit;
148}
149
551ce28f
EW
150sub version {
151 print "git-svn version $VERSION\n";
152 exit 0;
153}
154
3397f9df
EW
155sub rebuild {
156 $SVN_URL = shift or undef;
3397f9df 157 my $newest_rev = 0;
2beb3cdd
EW
158 if ($_upgrade) {
159 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
160 } else {
161 check_upgrade_needed();
162 }
3397f9df
EW
163
164 my $pid = open(my $rev_list,'-|');
165 defined $pid or croak $!;
166 if ($pid == 0) {
2beb3cdd 167 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
3397f9df 168 }
2beb3cdd 169 my $latest;
3397f9df
EW
170 while (<$rev_list>) {
171 chomp;
172 my $c = $_;
173 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
174 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
175 next if (!@commit); # skip merges
176 my $id = $commit[$#commit];
177 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
178 \s([a-f\d\-]+)$/x);
179 if (!$rev || !$uuid || !$url) {
180 # some of the original repositories I made had
181 # indentifiers like this:
182 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)
183 \@([a-f\d\-]+)/x);
184 if (!$rev || !$uuid) {
185 croak "Unable to extract revision or UUID from ",
186 "$c, $id\n";
187 }
188 }
2beb3cdd
EW
189
190 # if we merged or otherwise started elsewhere, this is
191 # how we break out of it
1ca72aef 192 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
779b1446 193 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
2beb3cdd 194
3397f9df 195 print "r$rev = $c\n";
2beb3cdd 196 unless (defined $latest) {
3397f9df
EW
197 if (!$SVN_URL && !$url) {
198 croak "SVN repository location required: $url\n";
199 }
200 $SVN_URL ||= $url;
1d52aba8
EW
201 $SVN_UUID ||= $uuid;
202 setup_git_svn();
2beb3cdd 203 $latest = $rev;
3397f9df
EW
204 }
205 assert_revision_eq_or_unknown($rev, $c);
883d0a78 206 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
3397f9df
EW
207 $newest_rev = $rev if ($rev > $newest_rev);
208 }
209 close $rev_list or croak $?;
210 if (!chdir $SVN_WC) {
1d52aba8 211 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
3397f9df
EW
212 chdir $SVN_WC or croak $!;
213 }
214
215 $pid = fork;
216 defined $pid or croak $!;
217 if ($pid == 0) {
218 my @svn_up = qw(svn up);
219 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
220 sys(@svn_up,"-r$newest_rev");
221 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
36f5b1f0 222 index_changes();
3397f9df
EW
223 exec('git-write-tree');
224 }
225 waitpid $pid, 0;
2beb3cdd
EW
226
227 if ($_upgrade) {
228 print STDERR <<"";
229Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
230when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
231
232 }
3397f9df
EW
233}
234
235sub init {
81c5a0e6
EW
236 $SVN_URL = shift or die "SVN repository location required " .
237 "as a command-line argument\n";
3397f9df
EW
238 unless (-d $GIT_DIR) {
239 sys('git-init-db');
240 }
241 setup_git_svn();
242}
243
244sub fetch {
245 my (@parents) = @_;
2beb3cdd 246 check_upgrade_needed();
883d0a78 247 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
3397f9df 248 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
defc6492
EW
249 unless ($_revision) {
250 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
3397f9df 251 }
defc6492 252 push @log_args, "-r$_revision";
3397f9df
EW
253 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
254
ce6f3519 255 my $svn_log = svn_log_raw(@log_args);
3397f9df 256
03823184 257 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
3397f9df
EW
258 my $last_commit = undef;
259 unless (-d $SVN_WC) {
1d52aba8 260 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
3397f9df 261 chdir $SVN_WC or croak $!;
1d52aba8 262 read_uuid();
3397f9df 263 $last_commit = git_commit($base, @parents);
36f5b1f0 264 assert_tree($last_commit);
3397f9df
EW
265 } else {
266 chdir $SVN_WC or croak $!;
1d52aba8 267 read_uuid();
6dfbe516
EW
268 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
269 # looks like a user manually cp'd and svn switch'ed
270 unless ($last_commit) {
271 sys(qw/svn revert -R ./);
272 assert_svn_wc_clean($base->{revision});
273 $last_commit = git_commit($base, @parents);
274 assert_tree($last_commit);
275 }
3397f9df
EW
276 }
277 my @svn_up = qw(svn up);
278 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
03823184
EW
279 my $last = $base;
280 while (my $log_msg = next_log_entry($svn_log)) {
36f5b1f0 281 assert_tree($last_commit);
03823184
EW
282 if ($last->{revision} >= $log_msg->{revision}) {
283 croak "Out of order: last >= current: ",
284 "$last->{revision} >= $log_msg->{revision}\n";
285 }
36f5b1f0
EW
286 # Revert is needed for cases like:
287 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
288 # I can't seem to reproduce something like that on a test...
289 sys(qw/svn revert -R ./);
290 assert_svn_wc_clean($last->{revision});
03823184 291 sys(@svn_up,"-r$log_msg->{revision}");
3397f9df 292 $last_commit = git_commit($log_msg, $last_commit, @parents);
03823184 293 $last = $log_msg;
3397f9df 294 }
7f60b228
EW
295 unless (-e "$GIT_DIR/refs/heads/master") {
296 sys(qw(git-update-ref refs/heads/master),$last_commit);
297 }
03823184 298 return $last;
3397f9df
EW
299}
300
301sub commit {
302 my (@commits) = @_;
2beb3cdd 303 check_upgrade_needed();
3397f9df
EW
304 if ($_stdin || !@commits) {
305 print "Reading from stdin...\n";
306 @commits = ();
307 while (<STDIN>) {
1ca72aef 308 if (/\b($sha1_short)\b/o) {
3397f9df
EW
309 unshift @commits, $1;
310 }
311 }
312 }
313 my @revs;
8de010ad
EW
314 foreach my $c (@commits) {
315 chomp(my @tmp = safe_qx('git-rev-parse',$c));
316 if (scalar @tmp == 1) {
317 push @revs, $tmp[0];
318 } elsif (scalar @tmp > 1) {
319 push @revs, reverse (safe_qx('git-rev-list',@tmp));
320 } else {
321 die "Failed to rev-parse $c\n";
322 }
3397f9df
EW
323 }
324 chomp @revs;
325
b63af9b3 326 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
1d52aba8 327 my $info = svn_info('.');
b63af9b3
EW
328 my $fetched = fetch();
329 if ($info->{Revision} != $fetched->{revision}) {
330 print STDERR "There are new revisions that were fetched ",
331 "and need to be merged (or acknowledged) ",
332 "before committing.\n";
333 exit 1;
334 }
335 $info = svn_info('.');
1d52aba8
EW
336 read_uuid($info);
337 my $svn_current_rev = $info->{'Last Changed Rev'};
3397f9df 338 foreach my $c (@revs) {
cf52b8f0
EW
339 my $mods = svn_checkout_tree($svn_current_rev, $c);
340 if (scalar @$mods == 0) {
341 print "Skipping, no changes detected\n";
342 next;
343 }
3397f9df
EW
344 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
345 }
346 print "Done committing ",scalar @revs," revisions to SVN\n";
3397f9df
EW
347}
348
8f22562c
EW
349sub show_ignore {
350 require File::Find or die $!;
351 my $exclude_file = "$GIT_DIR/info/exclude";
352 open my $fh, '<', $exclude_file or croak $!;
353 chomp(my @excludes = (<$fh>));
354 close $fh or croak $!;
355
883d0a78 356 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
8f22562c
EW
357 chdir $SVN_WC or croak $!;
358 my %ign;
359 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
360 s#^\./##;
8a97e368 361 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
8f22562c
EW
362 }}, no_chdir=>1},'.');
363
364 print "\n# /\n";
365 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
366 delete $ign{'.'};
367 foreach my $i (sort keys %ign) {
368 print "\n# ",$i,"\n";
369 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
370 }
371}
372
3397f9df
EW
373########################### utility functions #########################
374
1d52aba8
EW
375sub read_uuid {
376 return if $SVN_UUID;
377 my $info = shift || svn_info('.');
378 $SVN_UUID = $info->{'Repository UUID'} or
379 croak "Repository UUID unreadable\n";
883d0a78
EW
380 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
381}
382
383sub quiet_run {
384 my $pid = fork;
385 defined $pid or croak $!;
386 if (!$pid) {
387 open my $null, '>', '/dev/null' or croak $!;
388 open STDERR, '>&', $null or croak $!;
389 open STDOUT, '>&', $null or croak $!;
390 exec @_ or croak $!;
391 }
392 waitpid $pid, 0;
393 return $?;
394}
395
396sub repo_path_split {
397 my $full_url = shift;
398 $full_url =~ s#/+$##;
399
400 foreach (@repo_path_split_cache) {
401 if ($full_url =~ s#$_##) {
402 my $u = $1;
403 $full_url =~ s#^/+##;
404 return ($u, $full_url);
405 }
406 }
407
408 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
409 $path =~ s#^/+##;
410 my @paths = split(m#/+#, $path);
411
412 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
413 my $n = shift @paths || last;
414 $url .= "/$n";
415 }
416 push @repo_path_split_cache, qr/^(\Q$url\E)/;
417 return ($url, $path);
1d52aba8
EW
418}
419
3397f9df
EW
420sub setup_git_svn {
421 defined $SVN_URL or croak "SVN repository location required\n";
422 unless (-d $GIT_DIR) {
423 croak "GIT_DIR=$GIT_DIR does not exist!\n";
424 }
883d0a78
EW
425 mkpath([$GIT_SVN_DIR]);
426 mkpath(["$GIT_SVN_DIR/info"]);
3397f9df 427 mkpath([$REV_DIR]);
883d0a78 428 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
3397f9df 429
883d0a78 430 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
3397f9df
EW
431 print $fd '.svn',"\n";
432 close $fd or croak $!;
883d0a78
EW
433 my ($url, $path) = repo_path_split($SVN_URL);
434 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
435 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
3397f9df
EW
436}
437
438sub assert_svn_wc_clean {
36f5b1f0 439 my ($svn_rev) = @_;
3397f9df 440 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
ce4c8b24
EW
441 my $lcr = svn_info('.')->{'Last Changed Rev'};
442 if ($svn_rev != $lcr) {
443 print STDERR "Checking for copy-tree ... ";
ce4c8b24
EW
444 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
445 "-r$lcr:$svn_rev")));
446 if (@diff) {
447 croak "Nope! Expected r$svn_rev, got r$lcr\n";
448 } else {
449 print STDERR "OK!\n";
450 }
3397f9df
EW
451 }
452 my @status = grep(!/^Performing status on external/,(`svn status`));
453 @status = grep(!/^\s*$/,@status);
454 if (scalar @status) {
455 print STDERR "Tree ($SVN_WC) is not clean:\n";
456 print STDERR $_ foreach @status;
457 croak;
458 }
cf52b8f0
EW
459}
460
461sub assert_tree {
462 my ($treeish) = @_;
463 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
464 chomp(my $type = `git-cat-file -t $treeish`);
465 my $expected;
466 while ($type eq 'tag') {
467 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
468 }
469 if ($type eq 'commit') {
470 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
471 ($expected) = ($expected =~ /^tree ($sha1)$/);
472 die "Unable to get tree from $treeish\n" unless $expected;
473 } elsif ($type eq 'tree') {
474 $expected = $treeish;
475 } else {
476 die "$treeish is a $type, expected tree, tag or commit\n";
477 }
478
479 my $old_index = $ENV{GIT_INDEX_FILE};
480 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
481 if (-e $tmpindex) {
482 unlink $tmpindex or croak $!;
483 }
484 $ENV{GIT_INDEX_FILE} = $tmpindex;
36f5b1f0 485 index_changes(1);
cf52b8f0
EW
486 chomp(my $tree = `git-write-tree`);
487 if ($old_index) {
488 $ENV{GIT_INDEX_FILE} = $old_index;
489 } else {
490 delete $ENV{GIT_INDEX_FILE};
491 }
492 if ($tree ne $expected) {
493 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
3397f9df 494 }
36f5b1f0 495 unlink $tmpindex;
3397f9df
EW
496}
497
498sub parse_diff_tree {
499 my $diff_fh = shift;
500 local $/ = "\0";
501 my $state = 'meta';
502 my @mods;
503 while (<$diff_fh>) {
504 chomp $_; # this gets rid of the trailing "\0"
3397f9df
EW
505 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
506 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
507 push @mods, { mode_a => $1, mode_b => $2,
508 sha1_b => $3, chg => $4 };
509 if ($4 =~ /^(?:C|R)$/) {
510 $state = 'file_a';
511 } else {
512 $state = 'file_b';
513 }
514 } elsif ($state eq 'file_a') {
cf52b8f0 515 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 516 if ($x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 517 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
518 }
519 $x->{file_a} = $_;
520 $state = 'file_b';
521 } elsif ($state eq 'file_b') {
cf52b8f0 522 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 523 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 524 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
525 }
526 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
cf52b8f0 527 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
528 }
529 $x->{file_b} = $_;
530 $state = 'meta';
531 } else {
cf52b8f0 532 croak "Error parsing $_\n";
3397f9df
EW
533 }
534 }
535 close $diff_fh or croak $!;
cf52b8f0 536
3397f9df
EW
537 return \@mods;
538}
539
540sub svn_check_prop_executable {
541 my $m = shift;
cf52b8f0
EW
542 return if -l $m->{file_b};
543 if ($m->{mode_b} =~ /755$/) {
544 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
545 if ($m->{mode_a} !~ /755$/) {
546 sys(qw(svn propset svn:executable 1), $m->{file_b});
547 }
548 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
3397f9df
EW
549 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
550 sys(qw(svn propdel svn:executable), $m->{file_b});
cf52b8f0
EW
551 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
552 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
3397f9df
EW
553 }
554}
555
556sub svn_ensure_parent_path {
557 my $dir_b = dirname(shift);
558 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
559 mkpath([$dir_b]) unless (-d $dir_b);
560 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
561}
562
cf52b8f0
EW
563sub precommit_check {
564 my $mods = shift;
565 my (%rm_file, %rmdir_check, %added_check);
566
567 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
568 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
569 if ($m->{chg} eq 'R') {
570 if (-d $m->{file_b}) {
571 err_dir_to_file("$m->{file_a} => $m->{file_b}");
572 }
573 # dir/$file => dir/file/$file
574 my $dirname = dirname($m->{file_b});
575 while ($dirname ne File::Spec->curdir) {
576 if ($dirname ne $m->{file_a}) {
577 $dirname = dirname($dirname);
578 next;
579 }
580 err_file_to_dir("$m->{file_a} => $m->{file_b}");
581 }
582 # baz/zzz => baz (baz is a file)
583 $dirname = dirname($m->{file_a});
584 while ($dirname ne File::Spec->curdir) {
585 if ($dirname ne $m->{file_b}) {
586 $dirname = dirname($dirname);
587 next;
588 }
589 err_dir_to_file("$m->{file_a} => $m->{file_b}");
590 }
591 }
592 if ($m->{chg} =~ /^(D|R)$/) {
593 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
594 $rm_file{ $m->{$t} } = 1;
595 my $dirname = dirname( $m->{$t} );
596 my $basename = basename( $m->{$t} );
597 $rmdir_check{$dirname}->{$basename} = 1;
598 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
599 if (-d $m->{file_b}) {
600 err_dir_to_file($m->{file_b});
601 }
602 my $dirname = dirname( $m->{file_b} );
603 my $basename = basename( $m->{file_b} );
604 $added_check{$dirname}->{$basename} = 1;
605 while ($dirname ne File::Spec->curdir) {
606 if ($rm_file{$dirname}) {
607 err_file_to_dir($m->{file_b});
608 }
609 $dirname = dirname $dirname;
610 }
611 }
612 }
613 return (\%rmdir_check, \%added_check);
614
615 sub err_dir_to_file {
616 my $file = shift;
617 print STDERR "Node change from directory to file ",
618 "is not supported by Subversion: ",$file,"\n";
619 exit 1;
620 }
621 sub err_file_to_dir {
622 my $file = shift;
623 print STDERR "Node change from file to directory ",
624 "is not supported by Subversion: ",$file,"\n";
625 exit 1;
626 }
627}
628
3397f9df 629sub svn_checkout_tree {
cf52b8f0 630 my ($svn_rev, $treeish) = @_;
3397f9df 631 my $from = file_to_s("$REV_DIR/$svn_rev");
36f5b1f0 632 assert_tree($from);
ac8e0b91 633 print "diff-tree $from $treeish\n";
3397f9df
EW
634 my $pid = open my $diff_fh, '-|';
635 defined $pid or croak $!;
636 if ($pid == 0) {
162f4129
EW
637 my @diff_tree = qw(git-diff-tree -z -r);
638 if ($_cp_similarity) {
639 push @diff_tree, "-C$_cp_similarity";
640 } else {
641 push @diff_tree, '-C';
642 }
72942938
EW
643 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
644 push @diff_tree, "-l$_l" if defined $_l;
cf52b8f0 645 exec(@diff_tree, $from, $treeish) or croak $!;
3397f9df
EW
646 }
647 my $mods = parse_diff_tree($diff_fh);
648 unless (@$mods) {
ac8e0b91 649 # git can do empty commits, but SVN doesn't allow it...
cf52b8f0 650 return $mods;
3397f9df 651 }
cf52b8f0
EW
652 my ($rm, $add) = precommit_check($mods);
653
654 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
655 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3397f9df
EW
656 if ($m->{chg} eq 'C') {
657 svn_ensure_parent_path( $m->{file_b} );
658 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
cf52b8f0 659 apply_mod_line_blob($m);
3397f9df
EW
660 svn_check_prop_executable($m);
661 } elsif ($m->{chg} eq 'D') {
3397f9df
EW
662 sys(qw(svn rm --force), $m->{file_b});
663 } elsif ($m->{chg} eq 'R') {
664 svn_ensure_parent_path( $m->{file_b} );
665 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
cf52b8f0 666 apply_mod_line_blob($m);
3397f9df 667 svn_check_prop_executable($m);
3397f9df 668 } elsif ($m->{chg} eq 'M') {
cf52b8f0 669 apply_mod_line_blob($m);
3397f9df
EW
670 svn_check_prop_executable($m);
671 } elsif ($m->{chg} eq 'T') {
672 sys(qw(svn rm --force),$m->{file_b});
cf52b8f0 673 apply_mod_line_blob($m);
3397f9df 674 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 675 svn_check_prop_executable($m);
3397f9df
EW
676 } elsif ($m->{chg} eq 'A') {
677 svn_ensure_parent_path( $m->{file_b} );
cf52b8f0 678 apply_mod_line_blob($m);
3397f9df 679 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 680 svn_check_prop_executable($m);
3397f9df
EW
681 } else {
682 croak "Invalid chg: $m->{chg}\n";
683 }
684 }
cf52b8f0
EW
685
686 assert_tree($treeish);
687 if ($_rmdir) { # remove empty directories
688 handle_rmdir($rm, $add);
689 }
690 assert_tree($treeish);
691 return $mods;
692}
693
694# svn ls doesn't work with respect to the current working tree, but what's
695# in the repository. There's not even an option for it... *sigh*
696# (added files don't show up and removed files remain in the ls listing)
697sub svn_ls_current {
698 my ($dir, $rm, $add) = @_;
699 chomp(my @ls = safe_qx('svn','ls',$dir));
700 my @ret = ();
701 foreach (@ls) {
702 s#/$##; # trailing slashes are evil
703 push @ret, $_ unless $rm->{$dir}->{$_};
704 }
705 if (exists $add->{$dir}) {
706 push @ret, keys %{$add->{$dir}};
707 }
708 return \@ret;
709}
710
711sub handle_rmdir {
712 my ($rm, $add) = @_;
713
714 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
715 my $ls = svn_ls_current($dir, $rm, $add);
716 next if (scalar @$ls);
717 sys(qw(svn rm --force),$dir);
718
719 my $dn = dirname $dir;
720 $rm->{ $dn }->{ basename $dir } = 1;
721 $ls = svn_ls_current($dn, $rm, $add);
722 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
723 sys(qw(svn rm --force),$dn);
724 $dir = basename $dn;
725 $dn = dirname $dn;
726 $rm->{ $dn }->{ $dir } = 1;
727 $ls = svn_ls_current($dn, $rm, $add);
3397f9df
EW
728 }
729 }
730}
731
732sub svn_commit_tree {
733 my ($svn_rev, $commit) = @_;
883d0a78 734 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
e17512f3 735 my %log_msg = ( msg => '' );
ac8e0b91 736 open my $msg, '>', $commit_msg or croak $!;
3397f9df
EW
737
738 chomp(my $type = `git-cat-file -t $commit`);
739 if ($type eq 'commit') {
740 my $pid = open my $msg_fh, '-|';
741 defined $pid or croak $!;
742
743 if ($pid == 0) {
744 exec(qw(git-cat-file commit), $commit) or croak $!;
745 }
746 my $in_msg = 0;
747 while (<$msg_fh>) {
748 if (!$in_msg) {
749 $in_msg = 1 if (/^\s*$/);
df746c5a
EW
750 } elsif (/^git-svn-id: /) {
751 # skip this, we regenerate the correct one
752 # on re-fetch anyways
3397f9df
EW
753 } else {
754 print $msg $_ or croak $!;
755 }
756 }
757 close $msg_fh or croak $!;
758 }
759 close $msg or croak $!;
760
761 if ($_edit || ($type eq 'tree')) {
762 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
763 system($editor, $commit_msg);
764 }
ac8e0b91
EW
765
766 # file_to_s removes all trailing newlines, so just use chomp() here:
767 open $msg, '<', $commit_msg or croak $!;
768 { local $/; chomp($log_msg{msg} = <$msg>); }
769 close $msg or croak $!;
770
771 my ($oneline) = ($log_msg{msg} =~ /([^\n\r]+)/);
772 print "Committing $commit: $oneline\n";
773
ce475dfc
EW
774 if (defined $LC_ALL) {
775 $ENV{LC_ALL} = $LC_ALL;
776 } else {
777 delete $ENV{LC_ALL};
778 }
3397f9df 779 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
ce475dfc 780 $ENV{LC_ALL} = 'C';
3397f9df 781 unlink $commit_msg;
ce475dfc
EW
782 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
783 if (!defined $committed) {
784 my $out = join("\n",@ci_output);
785 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
786 $out, "\n\nAssuming English locale...";
787 ($committed) = ($out =~ /^Committed revision \d+\./sm);
788 defined $committed or die " FAILED!\n",
3397f9df 789 "Commit output failed to parse committed revision!\n",
ce475dfc
EW
790 print STDERR " OK\n";
791 }
3397f9df 792
e17512f3 793 my @svn_up = qw(svn up);
3397f9df 794 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
ce475dfc
EW
795 if ($committed == ($svn_rev + 1)) {
796 push @svn_up, "-r$committed";
e17512f3
EW
797 sys(@svn_up);
798 my $info = svn_info('.');
799 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
ce475dfc
EW
800 if ($info->{'Last Changed Rev'} != $committed) {
801 croak "$info->{'Last Changed Rev'} != $committed\n"
e17512f3
EW
802 }
803 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
804 /(\d{4})\-(\d\d)\-(\d\d)\s
805 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
806 or croak "Failed to parse date: $date\n";
807 $log_msg{date} = "$tz $Y-$m-$d $H:$M:$S";
808 $log_msg{author} = $info->{'Last Changed Author'};
ce475dfc 809 $log_msg{revision} = $committed;
e17512f3
EW
810 $log_msg{msg} .= "\n";
811 my $parent = file_to_s("$REV_DIR/$svn_rev");
812 git_commit(\%log_msg, $parent, $commit);
ce475dfc 813 return $committed;
e17512f3
EW
814 }
815 # resync immediately
816 push @svn_up, "-r$svn_rev";
3397f9df 817 sys(@svn_up);
ce475dfc 818 return fetch("$committed=$commit")->{revision};
3397f9df
EW
819}
820
03823184
EW
821# read the entire log into a temporary file (which is removed ASAP)
822# and store the file handle + parser state
3397f9df
EW
823sub svn_log_raw {
824 my (@log_args) = @_;
03823184
EW
825 my $log_fh = IO::File->new_tmpfile or croak $!;
826 my $pid = fork;
3397f9df 827 defined $pid or croak $!;
03823184
EW
828 if (!$pid) {
829 open STDOUT, '>&', $log_fh or croak $!;
3397f9df
EW
830 exec (qw(svn log), @log_args) or croak $!
831 }
03823184
EW
832 waitpid $pid, 0;
833 croak if $?;
834 seek $log_fh, 0, 0 or croak $!;
835 return { state => 'sep', fh => $log_fh };
836}
837
838sub next_log_entry {
839 my $log = shift; # retval of svn_log_raw()
840 my $ret = undef;
841 my $fh = $log->{fh};
3397f9df 842
03823184 843 while (<$fh>) {
3397f9df
EW
844 chomp;
845 if (/^\-{72}$/) {
03823184
EW
846 if ($log->{state} eq 'msg') {
847 if ($ret->{lines}) {
848 $ret->{msg} .= $_."\n";
849 unless(--$ret->{lines}) {
850 $log->{state} = 'sep';
ce6f3519
EW
851 }
852 } else {
853 croak "Log parse error at: $_\n",
03823184 854 $ret->{revision},
ce6f3519
EW
855 "\n";
856 }
857 next;
858 }
03823184 859 if ($log->{state} ne 'sep') {
ce6f3519 860 croak "Log parse error at: $_\n",
03823184
EW
861 "state: $log->{state}\n",
862 $ret->{revision},
ce6f3519
EW
863 "\n";
864 }
03823184 865 $log->{state} = 'rev';
3397f9df
EW
866
867 # if we have an empty log message, put something there:
03823184
EW
868 if ($ret) {
869 $ret->{msg} ||= "\n";
870 delete $ret->{lines};
871 return $ret;
3397f9df
EW
872 }
873 next;
874 }
03823184 875 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
3397f9df 876 my $rev = $1;
ce6f3519
EW
877 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
878 ($lines) = ($lines =~ /(\d+)/);
3397f9df
EW
879 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
880 /(\d{4})\-(\d\d)\-(\d\d)\s
881 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
882 or croak "Failed to parse date: $date\n";
03823184 883 $ret = { revision => $rev,
3397f9df
EW
884 date => "$tz $Y-$m-$d $H:$M:$S",
885 author => $author,
ce6f3519 886 lines => $lines,
03823184 887 msg => '' };
a9612be2
EW
888 if (defined $_authors && ! defined $users{$author}) {
889 die "Author: $author not defined in ",
890 "$_authors file\n";
891 }
03823184 892 $log->{state} = 'msg_start';
3397f9df
EW
893 next;
894 }
895 # skip the first blank line of the message:
03823184
EW
896 if ($log->{state} eq 'msg_start' && /^$/) {
897 $log->{state} = 'msg';
898 } elsif ($log->{state} eq 'msg') {
899 if ($ret->{lines}) {
900 $ret->{msg} .= $_."\n";
901 unless (--$ret->{lines}) {
902 $log->{state} = 'sep';
ce6f3519
EW
903 }
904 } else {
905 croak "Log parse error at: $_\n",
03823184 906 $ret->{revision},"\n";
ce6f3519 907 }
3397f9df
EW
908 }
909 }
03823184 910 return $ret;
3397f9df
EW
911}
912
913sub svn_info {
914 my $url = shift || $SVN_URL;
915
916 my $pid = open my $info_fh, '-|';
917 defined $pid or croak $!;
918
919 if ($pid == 0) {
920 exec(qw(svn info),$url) or croak $!;
921 }
922
923 my $ret = {};
924 # only single-lines seem to exist in svn info output
925 while (<$info_fh>) {
926 chomp $_;
e17512f3 927 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
3397f9df
EW
928 $ret->{$1} = $2;
929 push @{$ret->{-order}}, $1;
930 }
931 }
932 close $info_fh or croak $!;
933 return $ret;
934}
935
936sub sys { system(@_) == 0 or croak $? }
937
36f5b1f0
EW
938sub eol_cp {
939 my ($from, $to) = @_;
8a97e368 940 my $es = svn_propget_base('svn:eol-style', $to);
36f5b1f0
EW
941 open my $rfd, '<', $from or croak $!;
942 binmode $rfd or croak $!;
943 open my $wfd, '>', $to or croak $!;
944 binmode $wfd or croak $!;
945
946 my $eol = $EOL{$es} or undef;
36f5b1f0 947 my $buf;
4a393f2b 948 use bytes;
36f5b1f0
EW
949 while (1) {
950 my ($r, $w, $t);
951 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
952 return unless $r;
4a393f2b
EW
953 if ($eol) {
954 if ($buf =~ /\015$/) {
955 my $c;
956 defined($r = sysread($rfd,$c,1)) or croak $!;
957 $buf .= $c if $r > 0;
958 }
959 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
960 $r = length($buf);
961 }
36f5b1f0
EW
962 for ($w = 0; $w < $r; $w += $t) {
963 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
964 }
965 }
4a393f2b 966 no bytes;
36f5b1f0
EW
967}
968
969sub do_update_index {
970 my ($z_cmd, $cmd, $no_text_base) = @_;
971
972 my $z = open my $p, '-|';
973 defined $z or croak $!;
974 unless ($z) { exec @$z_cmd or croak $! }
975
976 my $pid = open my $ui, '|-';
977 defined $pid or croak $!;
978 unless ($pid) {
979 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
980 }
981 local $/ = "\0";
982 while (my $x = <$p>) {
983 chomp $x;
984 if (!$no_text_base && lstat $x && ! -l _ &&
8a97e368 985 svn_propget_base('svn:keywords', $x)) {
36f5b1f0
EW
986 my $mode = -x _ ? 0755 : 0644;
987 my ($v,$d,$f) = File::Spec->splitpath($x);
988 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
989 'text-base',"$f.svn-base");
990 $tb =~ s#^/##;
991 unless (-f $tb) {
992 $tb = File::Spec->catfile($d, '.svn',
993 'text-base',"$f.svn-base");
994 $tb =~ s#^/##;
995 }
996 unlink $x or croak $!;
997 eol_cp($tb, $x);
998 chmod(($mode &~ umask), $x) or croak $!;
999 }
1000 print $ui $x,"\0";
1001 }
1002 close $ui or croak $!;
1003}
1004
1005sub index_changes {
1006 my $no_text_base = shift;
1007 do_update_index([qw/git-diff-files --name-only -z/],
1008 'remove',
1009 $no_text_base);
1010 do_update_index([qw/git-ls-files -z --others/,
883d0a78 1011 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
36f5b1f0
EW
1012 'add',
1013 $no_text_base);
3397f9df
EW
1014}
1015
1016sub s_to_file {
1017 my ($str, $file, $mode) = @_;
1018 open my $fd,'>',$file or croak $!;
1019 print $fd $str,"\n" or croak $!;
1020 close $fd or croak $!;
1021 chmod ($mode &~ umask, $file) if (defined $mode);
1022}
1023
1024sub file_to_s {
1025 my $file = shift;
1026 open my $fd,'<',$file or croak "$!: file: $file\n";
1027 local $/;
1028 my $ret = <$fd>;
1029 close $fd or croak $!;
1030 $ret =~ s/\s*$//s;
1031 return $ret;
1032}
1033
1034sub assert_revision_unknown {
1035 my $revno = shift;
1036 if (-f "$REV_DIR/$revno") {
1037 croak "$REV_DIR/$revno already exists! ",
1038 "Why are we refetching it?";
1039 }
1040}
1041
ac749050
EW
1042sub trees_eq {
1043 my ($x, $y) = @_;
1044 my @x = safe_qx('git-cat-file','commit',$x);
1045 my @y = safe_qx('git-cat-file','commit',$y);
1046 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1047 || $y[0] !~ /^tree $sha1\n$/) {
1048 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1049 return 0
1050 }
1051 return 1;
1052}
1053
3397f9df
EW
1054sub assert_revision_eq_or_unknown {
1055 my ($revno, $commit) = @_;
1056 if (-f "$REV_DIR/$revno") {
1057 my $current = file_to_s("$REV_DIR/$revno");
ac749050 1058 if (($commit ne $current) && !trees_eq($commit, $current)) {
3397f9df
EW
1059 croak "$REV_DIR/$revno already exists!\n",
1060 "current: $current\nexpected: $commit\n";
1061 }
1062 return;
1063 }
1064}
1065
1066sub git_commit {
1067 my ($log_msg, @parents) = @_;
1068 assert_revision_unknown($log_msg->{revision});
1069 my $out_fh = IO::File->new_tmpfile or croak $!;
3397f9df 1070
69f0d91e
EW
1071 map_tree_joins() if (@_branch_from && !%tree_map);
1072
3397f9df
EW
1073 # commit parents can be conditionally bound to a particular
1074 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1075 my @exec_parents;
1076 foreach my $p (@parents) {
1077 next unless defined $p;
1078 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1079 if ($1 == $log_msg->{revision}) {
1080 push @exec_parents, $2;
1081 }
1082 } else {
1083 push @exec_parents, $p if $p =~ /$sha1_short/o;
1084 }
1085 }
1086
1087 my $pid = fork;
1088 defined $pid or croak $!;
1089 if ($pid == 0) {
1090 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
36f5b1f0 1091 index_changes();
3397f9df
EW
1092 chomp(my $tree = `git-write-tree`);
1093 croak if $?;
69f0d91e
EW
1094 if (exists $tree_map{$tree}) {
1095 my %seen_parent = map { $_ => 1 } @exec_parents;
1096 foreach (@{$tree_map{$tree}}) {
1097 # MAXPARENT is defined to 16 in commit-tree.c:
1098 if ($seen_parent{$_} || @exec_parents > 16) {
1099 next;
1100 }
1101 push @exec_parents, $_;
1102 $seen_parent{$_} = 1;
1103 }
1104 }
3397f9df
EW
1105 my $msg_fh = IO::File->new_tmpfile or croak $!;
1106 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1107 "$SVN_URL\@$log_msg->{revision}",
1ca72aef 1108 " $SVN_UUID\n" or croak $!;
3397f9df
EW
1109 $msg_fh->flush == 0 or croak $!;
1110 seek $msg_fh, 0, 0 or croak $!;
1111
1ca72aef 1112 set_commit_env($log_msg);
a9612be2 1113
3397f9df
EW
1114 my @exec = ('git-commit-tree',$tree);
1115 push @exec, '-p', $_ foreach @exec_parents;
1116 open STDIN, '<&', $msg_fh or croak $!;
1117 open STDOUT, '>&', $out_fh or croak $!;
1118 exec @exec or croak $!;
1119 }
1120 waitpid($pid,0);
1121 croak if $?;
1122
1123 $out_fh->flush == 0 or croak $!;
1124 seek $out_fh, 0, 0 or croak $!;
1125 chomp(my $commit = do { local $/; <$out_fh> });
1126 if ($commit !~ /^$sha1$/o) {
1127 croak "Failed to commit, invalid sha1: $commit\n";
1128 }
2beb3cdd 1129 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
3397f9df 1130 if (my $primary_parent = shift @exec_parents) {
1d52aba8
EW
1131 $pid = fork;
1132 defined $pid or croak $!;
1133 if (!$pid) {
1134 close STDERR;
1135 close STDOUT;
1136 exec 'git-rev-parse','--verify',
1137 "refs/remotes/$GIT_SVN^0";
1138 }
1139 waitpid $pid, 0;
1140 push @update_ref, $primary_parent unless $?;
3397f9df
EW
1141 }
1142 sys(@update_ref);
883d0a78 1143 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
3397f9df
EW
1144 print "r$log_msg->{revision} = $commit\n";
1145 return $commit;
1146}
1147
a9612be2 1148sub set_commit_env {
1ca72aef 1149 my ($log_msg) = @_;
a9612be2
EW
1150 my $author = $log_msg->{author};
1151 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1ca72aef 1152 : ($author,"$author\@$SVN_UUID");
a9612be2
EW
1153 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1154 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1155 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1156}
1157
cf52b8f0
EW
1158sub apply_mod_line_blob {
1159 my $m = shift;
1160 if ($m->{mode_b} =~ /^120/) {
1161 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1162 } else {
1163 blob_to_file($m->{sha1_b}, $m->{file_b});
1164 }
1165}
1166
3397f9df
EW
1167sub blob_to_symlink {
1168 my ($blob, $link) = @_;
1169 defined $link or croak "\$link not defined!\n";
1170 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
1171 if (-l $link || -f _) {
1172 unlink $link or croak $!;
1173 }
1174
3397f9df
EW
1175 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1176 symlink $dest, $link or croak $!;
1177}
1178
1179sub blob_to_file {
1180 my ($blob, $file) = @_;
1181 defined $file or croak "\$file not defined!\n";
1182 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
1183 if (-l $file || -f _) {
1184 unlink $file or croak $!;
1185 }
1186
3397f9df
EW
1187 open my $blob_fh, '>', $file or croak "$!: $file\n";
1188 my $pid = fork;
1189 defined $pid or croak $!;
1190
1191 if ($pid == 0) {
1192 open STDOUT, '>&', $blob_fh or croak $!;
1193 exec('git-cat-file','blob',$blob);
1194 }
1195 waitpid $pid, 0;
1196 croak $? if $?;
1197
1198 close $blob_fh or croak $!;
1199}
1200
1201sub safe_qx {
1202 my $pid = open my $child, '-|';
1203 defined $pid or croak $!;
1204 if ($pid == 0) {
1205 exec(@_) or croak $?;
1206 }
1207 my @ret = (<$child>);
1208 close $child or croak $?;
1209 die $? if $?; # just in case close didn't error out
1210 return wantarray ? @ret : join('',@ret);
1211}
1212
1d52aba8
EW
1213sub svn_compat_check {
1214 my @co_help = safe_qx(qw(svn co -h));
1215 unless (grep /ignore-externals/,@co_help) {
3397f9df
EW
1216 print STDERR "W: Installed svn version does not support ",
1217 "--ignore-externals\n";
1218 $_no_ignore_ext = 1;
1219 }
1d52aba8
EW
1220 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1221 $_svn_co_url_revs = 1;
1222 }
8a97e368
EW
1223 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1224 $_svn_pg_peg_revs = 1;
1225 }
7317ed90
EW
1226
1227 # I really, really hope nobody hits this...
1228 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1229 print STDERR <<'';
1230W: The installed svn version does not support the --stop-on-copy flag in
1231 the log command.
1232 Lets hope the directory you're tracking is not a branch or tag
1233 and was never moved within the repository...
1234
1235 $_no_stop_copy = 1;
1236 }
1d52aba8
EW
1237}
1238
1239# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1240# (and they won't honor URL@<rev> without -r<rev>, too!)
1241sub svn_cmd_checkout {
1242 my ($url, $rev, $dir) = @_;
1243 my @cmd = ('svn','co', "-r$rev");
1244 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1245 $url .= "\@$rev" if $_svn_co_url_revs;
1246 sys(@cmd, $url, $dir);
3397f9df 1247}
2beb3cdd
EW
1248
1249sub check_upgrade_needed {
1250 my $old = eval {
1251 my $pid = open my $child, '-|';
1252 defined $pid or croak $!;
1253 if ($pid == 0) {
1254 close STDERR;
1255 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $?;
1256 }
1257 my @ret = (<$child>);
1258 close $child or croak $?;
1259 die $? if $?; # just in case close didn't error out
1260 return wantarray ? @ret : join('',@ret);
1261 };
1262 return unless $old;
1263 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1264 if ($@ || !$head) {
1265 print STDERR "Please run: $0 rebuild --upgrade\n";
1266 exit 1;
1267 }
1268}
1269
69f0d91e
EW
1270# fills %tree_map with a reverse mapping of trees to commits. Useful
1271# for finding parents to commit on.
1272sub map_tree_joins {
098749d9 1273 my %seen;
69f0d91e
EW
1274 foreach my $br (@_branch_from) {
1275 my $pid = open my $pipe, '-|';
1276 defined $pid or croak $!;
1277 if ($pid == 0) {
098749d9
EW
1278 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1279 or croak $?;
69f0d91e
EW
1280 }
1281 while (<$pipe>) {
1282 if (/^commit ($sha1)$/o) {
1283 my $commit = $1;
098749d9
EW
1284
1285 # if we've seen a commit,
1286 # we've seen its parents
1287 last if $seen{$commit};
69f0d91e
EW
1288 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1289 unless (defined $tree) {
1290 die "Failed to parse commit $commit\n";
1291 }
1292 push @{$tree_map{$tree}}, $commit;
098749d9 1293 $seen{$commit} = 1;
69f0d91e
EW
1294 }
1295 }
098749d9 1296 close $pipe; # we could be breaking the pipe early
69f0d91e
EW
1297 }
1298}
1299
bf78b1d8
EW
1300sub load_all_refs {
1301 if (@_branch_from) {
1302 print STDERR '--branch|-b parameters are ignored when ',
1303 "--branch-all-refs|-B is passed\n";
1304 }
1305
1306 # don't worry about rev-list on non-commit objects/tags,
1307 # it shouldn't blow up if a ref is a blob or tree...
1308 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1309}
1310
eeb0abe0
EW
1311# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1312sub load_authors {
1313 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1314 while (<$authors>) {
1315 chomp;
1316 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1317 my ($user, $name, $email) = ($1, $2, $3);
1318 $users{$user} = [$name, $email];
1319 }
1320 close $authors or croak $!;
1321}
1322
8a97e368
EW
1323sub svn_propget_base {
1324 my ($p, $f) = @_;
1325 $f .= '@BASE' if $_svn_pg_peg_revs;
1326 return safe_qx(qw/svn propget/, $p, $f);
1327}
1328
883d0a78
EW
1329sub migration_check {
1330 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1331 print "Upgrading repository...\n";
1332 unless (-d "$GIT_DIR/svn") {
1333 mkdir "$GIT_DIR/svn" or croak $!;
1334 }
1335 print "Data from a previous version of git-svn exists, but\n\t",
1336 "$GIT_SVN_DIR\n\t(required for this version ",
1337 "($VERSION) of git-svn) does not.\n";
1338
1339 foreach my $x (`git-rev-parse --symbolic --all`) {
1340 next unless $x =~ s#^refs/remotes/##;
1341 chomp $x;
1342 next unless -f "$GIT_DIR/$x/info/url";
1343 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1344 next unless $u;
1345 my $dn = dirname("$GIT_DIR/svn/$x");
1346 mkpath([$dn]) unless -d $dn;
1347 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1348 my ($url, $path) = repo_path_split($u);
1349 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
1350 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
1351 }
1352 print "Done upgrading.\n";
1353}
1354
3397f9df
EW
1355__END__
1356
1357Data structures:
1358
03823184
EW
1359$svn_log hashref (as returned by svn_log_raw)
1360{
1361 fh => file handle of the log file,
1362 state => state of the log file parser (sep/msg/rev/msg_start...)
1363}
3397f9df 1364
03823184 1365$log_msg hashref as returned by next_log_entry($svn_log)
3397f9df
EW
1366{
1367 msg => 'whitespace-formatted log entry
1368', # trailing newline is preserved
1369 revision => '8', # integer
1370 date => '2004-02-24T17:01:44.108345Z', # commit date
1371 author => 'committer name'
1372};
1373
1374
1375@mods = array of diff-index line hashes, each element represents one line
1376 of diff-index output
1377
1378diff-index line ($m hash)
1379{
1380 mode_a => first column of diff-index output, no leading ':',
1381 mode_b => second column of diff-index output,
1382 sha1_b => sha1sum of the final blob,
ac8e0b91 1383 chg => change type [MCRADT],
3397f9df
EW
1384 file_a => original file name of a file (iff chg is 'C' or 'R')
1385 file_b => new/current file name of a file (any chg)
1386}
1387;