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