git-svn: add support for Perl SVN::* libraries
[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};
79bb8d88 18my $TZ = $ENV{TZ};
3397f9df
EW
19# make sure the svn binary gives consistent output between locales and TZs:
20$ENV{TZ} = 'UTC';
21$ENV{LC_ALL} = 'C';
22
23# If SVN:: library support is added, please make the dependencies
24# optional and preserve the capability to use the command-line client.
ce6f3519 25# use eval { require SVN::... } to make it lazy load
eeb0abe0 26# We don't use any modules not in the standard Perl distribution:
3397f9df
EW
27use Carp qw/croak/;
28use IO::File qw//;
29use File::Basename qw/dirname basename/;
30use File::Path qw/mkpath/;
79bb8d88 31use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
3397f9df 32use File::Spec qw//;
e17512f3 33use POSIX qw/strftime/;
a5e0cedc
EW
34
35my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
36$_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
37libsvn_load();
3397f9df 38my $sha1 = qr/[a-f\d]{40}/;
ac8e0b91 39my $sha1_short = qr/[a-f\d]{4,40}/;
72942938 40my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
162f4129 41 $_find_copies_harder, $_l, $_cp_similarity,
dc5869c0 42 $_repack, $_repack_nr, $_repack_flags,
9d55b41a 43 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
79bb8d88 44 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
9d55b41a 45 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
79bb8d88 46my (@_branch_from, %tree_map, %users, %rusers);
8a97e368 47my ($_svn_co_url_revs, $_svn_pg_peg_revs);
883d0a78 48my @repo_path_split_cache;
3397f9df 49
eeb0abe0 50my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
69f0d91e 51 'branch|b=s' => \@_branch_from,
bf78b1d8 52 'branch-all-refs|B' => \$_branch_all_refs,
dc5869c0
EW
53 'authors-file|A=s' => \$_authors,
54 'repack:i' => \$_repack,
55 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
36f5b1f0 56
9d55b41a
EW
57my ($_trunk, $_tags, $_branches);
58my %multi_opts = ( 'trunk|T=s' => \$_trunk,
59 'tags|t=s' => \$_tags,
60 'branches|b=s' => \$_branches );
61my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
62
36f5b1f0
EW
63# yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
64my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
65
3397f9df 66my %cmd = (
eeb0abe0
EW
67 fetch => [ \&fetch, "Download new revisions from SVN",
68 { 'revision|r=s' => \$_revision, %fc_opts } ],
81c5a0e6 69 init => [ \&init, "Initialize a repo for tracking" .
f8ab6b73 70 " (requires URL argument)",
9d55b41a 71 \%init_opts ],
eeb0abe0
EW
72 commit => [ \&commit, "Commit git revisions to SVN",
73 { 'stdin|' => \$_stdin,
74 'edit|e' => \$_edit,
75 'rmdir' => \$_rmdir,
76 'find-copies-harder' => \$_find_copies_harder,
77 'l=i' => \$_l,
162f4129 78 'copy-similarity|C=i'=> \$_cp_similarity,
eeb0abe0
EW
79 %fc_opts,
80 } ],
a5e0cedc
EW
81 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
82 { 'revision|r=i' => \$_revision } ],
eeb0abe0
EW
83 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
84 { 'no-ignore-externals' => \$_no_ignore_ext,
85 'upgrade' => \$_upgrade } ],
9d55b41a
EW
86 'graft-branches' => [ \&graft_branches,
87 'Detect merges/branches from already imported history',
88 { 'merge-rx|m' => \@_opt_m,
89 'no-default-regex' => \$_no_default_regex,
90 'no-graft-copy' => \$_no_graft_copy } ],
91 'multi-init' => [ \&multi_init,
92 'Initialize multiple trees (like git-svnimport)',
93 { %multi_opts, %fc_opts } ],
94 'multi-fetch' => [ \&multi_fetch,
95 'Fetch multiple trees (like git-svnimport)',
96 \%fc_opts ],
79bb8d88
EW
97 'log' => [ \&show_log, 'Show commit logs',
98 { 'limit=i' => \$_limit,
99 'revision|r=s' => \$_revision,
100 'verbose|v' => \$_verbose,
101 'incremental' => \$_incremental,
102 'oneline' => \$_oneline,
103 'show-commit' => \$_show_commit,
104 'authors-file|A=s' => \$_authors,
105 } ],
3397f9df 106);
9d55b41a 107
3397f9df
EW
108my $cmd;
109for (my $i = 0; $i < @ARGV; $i++) {
110 if (defined $cmd{$ARGV[$i]}) {
111 $cmd = $ARGV[$i];
112 splice @ARGV, $i, 1;
113 last;
114 }
115};
116
448c81b4 117my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 118
b8c92cad 119read_repo_config(\%opts);
79bb8d88
EW
120my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
121 'version|V' => \$_version,
122 'id|i=s' => \$GIT_SVN);
123exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 124
dc5869c0 125set_default_vals();
3397f9df 126usage(0) if $_help;
551ce28f 127version() if $_version;
eeb0abe0 128usage(1) unless defined $cmd;
b8c92cad 129init_vars();
eeb0abe0 130load_authors() if $_authors;
bf78b1d8 131load_all_refs() if $_branch_all_refs;
1d52aba8 132svn_compat_check();
9d55b41a 133migration_check() unless $cmd =~ /^(?:init|multi-init)$/;
3397f9df
EW
134$cmd{$cmd}->[0]->(@ARGV);
135exit 0;
136
137####################### primary functions ######################
138sub usage {
139 my $exit = shift || 0;
140 my $fd = $exit ? \*STDERR : \*STDOUT;
141 print $fd <<"";
142git-svn - bidirectional operations between a single Subversion tree and git
143Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
144
145 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
146
147 foreach (sort keys %cmd) {
448c81b4 148 next if $cmd && $cmd ne $_;
ac8e0b91 149 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
150 foreach (keys %{$cmd{$_}->[2]}) {
151 # prints out arguments as they should be passed:
b8c92cad 152 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
448c81b4
EW
153 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
154 "--$_" : "-$_" }
155 split /\|/,$_)," $x\n";
156 }
3397f9df
EW
157 }
158 print $fd <<"";
448c81b4
EW
159\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
160arbitrary identifier if you're tracking multiple SVN branches/repositories in
161one git repository and want to keep them separate. See git-svn(1) for more
162information.
3397f9df
EW
163
164 exit $exit;
165}
166
551ce28f
EW
167sub version {
168 print "git-svn version $VERSION\n";
169 exit 0;
170}
171
3397f9df
EW
172sub rebuild {
173 $SVN_URL = shift or undef;
3397f9df 174 my $newest_rev = 0;
2beb3cdd
EW
175 if ($_upgrade) {
176 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
177 } else {
178 check_upgrade_needed();
179 }
3397f9df
EW
180
181 my $pid = open(my $rev_list,'-|');
182 defined $pid or croak $!;
183 if ($pid == 0) {
2beb3cdd 184 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
3397f9df 185 }
2beb3cdd 186 my $latest;
3397f9df
EW
187 while (<$rev_list>) {
188 chomp;
189 my $c = $_;
190 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
191 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
192 next if (!@commit); # skip merges
79bb8d88
EW
193 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
194 if (!$rev || !$uuid) {
195 croak "Unable to extract revision or UUID from ",
196 "$c, $commit[$#commit]\n";
3397f9df 197 }
2beb3cdd
EW
198
199 # if we merged or otherwise started elsewhere, this is
200 # how we break out of it
1ca72aef 201 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
779b1446 202 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
2beb3cdd 203
3397f9df 204 print "r$rev = $c\n";
2beb3cdd 205 unless (defined $latest) {
3397f9df
EW
206 if (!$SVN_URL && !$url) {
207 croak "SVN repository location required: $url\n";
208 }
209 $SVN_URL ||= $url;
1d52aba8
EW
210 $SVN_UUID ||= $uuid;
211 setup_git_svn();
2beb3cdd 212 $latest = $rev;
3397f9df
EW
213 }
214 assert_revision_eq_or_unknown($rev, $c);
883d0a78 215 sys('git-update-ref',"svn/$GIT_SVN/revs/$rev",$c);
3397f9df
EW
216 $newest_rev = $rev if ($rev > $newest_rev);
217 }
218 close $rev_list or croak $?;
a5e0cedc
EW
219
220 goto out if $_use_lib;
3397f9df 221 if (!chdir $SVN_WC) {
1d52aba8 222 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
3397f9df
EW
223 chdir $SVN_WC or croak $!;
224 }
225
226 $pid = fork;
227 defined $pid or croak $!;
228 if ($pid == 0) {
229 my @svn_up = qw(svn up);
230 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
231 sys(@svn_up,"-r$newest_rev");
232 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
36f5b1f0 233 index_changes();
b8c92cad 234 exec('git-write-tree') or croak $!;
3397f9df
EW
235 }
236 waitpid $pid, 0;
b8c92cad 237 croak $? if $?;
a5e0cedc 238out:
2beb3cdd
EW
239 if ($_upgrade) {
240 print STDERR <<"";
241Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
242when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
243
244 }
3397f9df
EW
245}
246
247sub init {
81c5a0e6
EW
248 $SVN_URL = shift or die "SVN repository location required " .
249 "as a command-line argument\n";
9d55b41a 250 $SVN_URL =~ s!/+$!!; # strip trailing slash
3397f9df 251 unless (-d $GIT_DIR) {
f8ab6b73
EW
252 my @init_db = ('git-init-db');
253 push @init_db, "--template=$_template" if defined $_template;
254 push @init_db, "--shared" if defined $_shared;
255 sys(@init_db);
3397f9df
EW
256 }
257 setup_git_svn();
258}
259
260sub fetch {
2beb3cdd 261 check_upgrade_needed();
883d0a78 262 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
263 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
264 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
265 refs/heads/master^0))) {
266 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
267 }
268 return $ret;
269}
270
271sub fetch_cmd {
272 my (@parents) = @_;
3397f9df 273 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
defc6492
EW
274 unless ($_revision) {
275 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
3397f9df 276 }
defc6492 277 push @log_args, "-r$_revision";
3397f9df
EW
278 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
279
ce6f3519 280 my $svn_log = svn_log_raw(@log_args);
3397f9df 281
03823184 282 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
3397f9df
EW
283 my $last_commit = undef;
284 unless (-d $SVN_WC) {
1d52aba8 285 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
3397f9df 286 chdir $SVN_WC or croak $!;
1d52aba8 287 read_uuid();
3397f9df 288 $last_commit = git_commit($base, @parents);
36f5b1f0 289 assert_tree($last_commit);
3397f9df
EW
290 } else {
291 chdir $SVN_WC or croak $!;
1d52aba8 292 read_uuid();
6dfbe516
EW
293 eval { $last_commit = file_to_s("$REV_DIR/$base->{revision}") };
294 # looks like a user manually cp'd and svn switch'ed
295 unless ($last_commit) {
296 sys(qw/svn revert -R ./);
297 assert_svn_wc_clean($base->{revision});
298 $last_commit = git_commit($base, @parents);
299 assert_tree($last_commit);
300 }
3397f9df
EW
301 }
302 my @svn_up = qw(svn up);
303 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
03823184
EW
304 my $last = $base;
305 while (my $log_msg = next_log_entry($svn_log)) {
36f5b1f0 306 assert_tree($last_commit);
03823184
EW
307 if ($last->{revision} >= $log_msg->{revision}) {
308 croak "Out of order: last >= current: ",
309 "$last->{revision} >= $log_msg->{revision}\n";
310 }
36f5b1f0
EW
311 # Revert is needed for cases like:
312 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
313 # I can't seem to reproduce something like that on a test...
314 sys(qw/svn revert -R ./);
315 assert_svn_wc_clean($last->{revision});
03823184 316 sys(@svn_up,"-r$log_msg->{revision}");
3397f9df 317 $last_commit = git_commit($log_msg, $last_commit, @parents);
03823184 318 $last = $log_msg;
3397f9df 319 }
b8c92cad 320 close $svn_log->{fh};
a5e0cedc 321 $last->{commit} = $last_commit;
03823184 322 return $last;
3397f9df
EW
323}
324
a5e0cedc
EW
325sub fetch_lib {
326 my (@parents) = @_;
327 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
328 my $repo;
329 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
330 $SVN_LOG ||= libsvn_connect($repo);
331 $SVN ||= libsvn_connect($repo);
332 my ($last_rev, $last_commit) = svn_grab_base_rev();
333 my ($base, $head) = libsvn_parse_revision($last_rev);
334 if ($base > $head) {
335 return { revision => $last_rev, commit => $last_commit }
336 }
337 my $index = set_index($GIT_SVN_INDEX);
338
339 # limit ourselves and also fork() since get_log won't release memory
340 # after processing a revision and SVN stuff seems to leak
341 my $inc = 1000;
342 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
343 read_uuid();
344 if (defined $last_commit) {
345 unless (-e $GIT_SVN_INDEX) {
346 sys(qw/git-read-tree/, $last_commit);
347 }
348 chomp (my $x = `git-write-tree`);
349 my ($y) = (`git-cat-file commit $last_commit`
350 =~ /^tree ($sha1)/m);
351 if ($y ne $x) {
352 unlink $GIT_SVN_INDEX or croak $!;
353 sys(qw/git-read-tree/, $last_commit);
354 }
355 chomp ($x = `git-write-tree`);
356 if ($y ne $x) {
357 print STDERR "trees ($last_commit) $y != $x\n",
358 "Something is seriously wrong...\n";
359 }
360 }
361 while (1) {
362 # fork, because using SVN::Pool with get_log() still doesn't
363 # seem to help enough to keep memory usage down.
364 defined(my $pid = fork) or croak $!;
365 if (!$pid) {
366 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
367 print "Fetching revisions $min .. $max\n";
368
369 # Yes I'm perfectly aware that the fourth argument
370 # below is the limit revisions number. Unfortunately
371 # performance sucks with it enabled, so it's much
372 # faster to fetch revision ranges instead of relying
373 # on the limiter.
374 $SVN_LOG->get_log( '/'.$SVN_PATH, $min, $max, 0, 1, 1,
375 sub {
376 my $log_msg;
377 if ($last_commit) {
378 $log_msg = libsvn_fetch(
379 $last_commit, @_);
380 $last_commit = git_commit(
381 $log_msg,
382 $last_commit,
383 @parents);
384 } else {
385 $log_msg = libsvn_new_tree(@_);
386 $last_commit = git_commit(
387 $log_msg, @parents);
388 }
389 });
390 $SVN::Error::handler = sub { 'quiet warnings' };
391 exit 0;
392 }
393 waitpid $pid, 0;
394 croak $? if $?;
395 ($last_rev, $last_commit) = svn_grab_base_rev();
396 last if ($max >= $head);
397 $min = $max + 1;
398 $max += $inc;
399 $max = $head if ($max > $head);
400 }
401 restore_index($index);
402 return { revision => $last_rev, commit => $last_commit };
403}
404
3397f9df
EW
405sub commit {
406 my (@commits) = @_;
2beb3cdd 407 check_upgrade_needed();
3397f9df
EW
408 if ($_stdin || !@commits) {
409 print "Reading from stdin...\n";
410 @commits = ();
411 while (<STDIN>) {
1ca72aef 412 if (/\b($sha1_short)\b/o) {
3397f9df
EW
413 unshift @commits, $1;
414 }
415 }
416 }
417 my @revs;
8de010ad
EW
418 foreach my $c (@commits) {
419 chomp(my @tmp = safe_qx('git-rev-parse',$c));
420 if (scalar @tmp == 1) {
421 push @revs, $tmp[0];
422 } elsif (scalar @tmp > 1) {
423 push @revs, reverse (safe_qx('git-rev-list',@tmp));
424 } else {
425 die "Failed to rev-parse $c\n";
426 }
3397f9df
EW
427 }
428 chomp @revs;
a5e0cedc
EW
429 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
430 print "Done committing ",scalar @revs," revisions to SVN\n";
431}
432
433sub commit_cmd {
434 my (@revs) = @_;
3397f9df 435
b63af9b3 436 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
1d52aba8 437 my $info = svn_info('.');
b63af9b3
EW
438 my $fetched = fetch();
439 if ($info->{Revision} != $fetched->{revision}) {
440 print STDERR "There are new revisions that were fetched ",
441 "and need to be merged (or acknowledged) ",
442 "before committing.\n";
443 exit 1;
444 }
445 $info = svn_info('.');
1d52aba8
EW
446 read_uuid($info);
447 my $svn_current_rev = $info->{'Last Changed Rev'};
3397f9df 448 foreach my $c (@revs) {
cf52b8f0
EW
449 my $mods = svn_checkout_tree($svn_current_rev, $c);
450 if (scalar @$mods == 0) {
451 print "Skipping, no changes detected\n";
452 next;
453 }
3397f9df
EW
454 $svn_current_rev = svn_commit_tree($svn_current_rev, $c);
455 }
3397f9df
EW
456}
457
a5e0cedc
EW
458sub commit_lib {
459 my (@revs) = @_;
460 my ($r_last, $cmt_last) = svn_grab_base_rev();
461 defined $r_last or die "Must have an existing revision to commit\n";
462 my $fetched = fetch_lib();
463 if ($r_last != $fetched->{revision}) {
464 print STDERR "There are new revisions that were fetched ",
465 "and need to be merged (or acknowledged) ",
466 "before committing.\n",
467 "last rev: $r_last\n",
468 " current: $fetched->{revision}\n";
469 exit 1;
470 }
471 read_uuid();
472 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
473 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
474
475 foreach my $c (@revs) {
476 # fork for each commit because there's a memory leak I
477 # can't track down... (it's probably in the SVN code)
478 defined(my $pid = open my $fh, '-|') or croak $!;
479 if (!$pid) {
480 if (defined $LC_ALL) {
481 $ENV{LC_ALL} = $LC_ALL;
482 } else {
483 delete $ENV{LC_ALL};
484 }
485 my $log_msg = get_commit_message($c, $commit_msg);
486 my $ed = SVN::Git::Editor->new(
487 { r => $r_last,
488 ra => $SVN,
489 c => $c,
490 svn_path => $SVN_PATH
491 },
492 $SVN->get_commit_editor(
493 $log_msg->{msg},
494 sub {
495 libsvn_commit_cb(
496 @_, $c,
497 $log_msg->{msg},
498 $r_last,
499 $cmt_last)
500 },
501 @lock)
502 );
503 my $mods = libsvn_checkout_tree($r_last, $c, $ed);
504 if (@$mods == 0) {
505 print "No changes\nr$r_last = $cmt_last\n";
506 $ed->abort_edit;
507 } else {
508 $ed->close_edit;
509 }
510 exit 0;
511 }
512 my ($r_new, $cmt_new, $no);
513 while (<$fh>) {
514 print $_;
515 chomp;
516 if (/^r(\d+) = ($sha1)$/o) {
517 ($r_new, $cmt_new) = ($1, $2);
518 } elsif ($_ eq 'No changes') {
519 $no = 1;
520 }
521 }
522 close $fh or croak $!;
523 if (! defined $r_new && ! defined $cmt_new) {
524 unless ($no) {
525 die "Failed to parse revision information\n";
526 }
527 } else {
528 ($r_last, $cmt_last) = ($r_new, $cmt_new);
529 }
530 }
531 unlink $commit_msg;
532}
8f22562c 533
a5e0cedc 534sub show_ignore {
883d0a78 535 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
536 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
537}
538
539sub show_ignore_cmd {
540 require File::Find or die $!;
541 if (defined $_revision) {
542 die "-r/--revision option doesn't work unless the Perl SVN ",
543 "libraries are used\n";
544 }
8f22562c
EW
545 chdir $SVN_WC or croak $!;
546 my %ign;
547 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
548 s#^\./##;
8a97e368 549 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
8f22562c
EW
550 }}, no_chdir=>1},'.');
551
552 print "\n# /\n";
553 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
554 delete $ign{'.'};
555 foreach my $i (sort keys %ign) {
556 print "\n# ",$i,"\n";
557 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
558 }
559}
560
a5e0cedc
EW
561sub show_ignore_lib {
562 my $repo;
563 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
564 $SVN ||= libsvn_connect($repo);
565 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
566 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
567}
568
9d55b41a
EW
569sub graft_branches {
570 my $gr_file = "$GIT_DIR/info/grafts";
571 my ($grafts, $comments) = read_grafts($gr_file);
572 my $gr_sha1;
573
574 if (%$grafts) {
575 # temporarily disable our grafts file to make this idempotent
576 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
577 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
578 }
579
580 my $l_map = read_url_paths();
581 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
582 unless ($_no_default_regex) {
583 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
584 qr/\b(?:from|of)\s+(\S.+)/is );
585 }
586 foreach my $u (keys %$l_map) {
587 if (@re) {
588 foreach my $p (keys %{$l_map->{$u}}) {
589 graft_merge_msg($grafts,$l_map,$u,$p);
590 }
591 }
a5e0cedc
EW
592 unless ($_no_graft_copy) {
593 if ($_use_lib) {
594 graft_file_copy_lib($grafts,$l_map,$u);
595 } else {
596 graft_file_copy_cmd($grafts,$l_map,$u);
597 }
598 }
9d55b41a
EW
599 }
600
601 write_grafts($grafts, $comments, $gr_file);
602 unlink "$gr_file~$gr_sha1" if $gr_sha1;
603}
604
605sub multi_init {
606 my $url = shift;
607 $_trunk ||= 'trunk';
608 $_trunk =~ s#/+$##;
609 $url =~ s#/+$## if $url;
610 if ($_trunk !~ m#^[a-z\+]+://#) {
611 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
612 unless ($url) {
613 print STDERR "E: '$_trunk' is not a complete URL ",
614 "and a separate URL is not specified\n";
615 exit 1;
616 }
617 $_trunk = $url . $_trunk;
618 }
619 if ($GIT_SVN eq 'git-svn') {
620 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
621 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
622 }
623 init_vars();
624 init($_trunk);
625 complete_url_ls_init($url, $_branches, '--branches/-b', '');
626 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
627}
628
629sub multi_fetch {
630 # try to do trunk first, since branches/tags
631 # may be descended from it.
632 if (-d "$GIT_DIR/svn/trunk") {
633 print "Fetching trunk\n";
634 defined(my $pid = fork) or croak $!;
635 if (!$pid) {
636 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
637 init_vars();
638 fetch(@_);
639 exit 0;
640 }
641 waitpid $pid, 0;
642 croak $? if $?;
643 }
644 rec_fetch('', "$GIT_DIR/svn", @_);
645}
646
79bb8d88
EW
647sub show_log {
648 my (@args) = @_;
649 my ($r_min, $r_max);
650 my $r_last = -1; # prevent dupes
651 rload_authors() if $_authors;
652 if (defined $TZ) {
653 $ENV{TZ} = $TZ;
654 } else {
655 delete $ENV{TZ};
656 }
657 if (defined $_revision) {
658 if ($_revision =~ /^(\d+):(\d+)$/) {
659 ($r_min, $r_max) = ($1, $2);
660 } elsif ($_revision =~ /^\d+$/) {
661 $r_min = $r_max = $_revision;
662 } else {
663 print STDERR "-r$_revision is not supported, use ",
664 "standard \'git log\' arguments instead\n";
665 exit 1;
666 }
667 }
668
669 my $pid = open(my $log,'-|');
670 defined $pid or croak $!;
671 if (!$pid) {
672 my @rl = (qw/git-log --abbrev-commit --pretty=raw
673 --default/, "remotes/$GIT_SVN");
674 push @rl, '--raw' if $_verbose;
675 exec(@rl, @args) or croak $!;
676 }
677 setup_pager();
678 my (@k, $c, $d);
679 while (<$log>) {
680 if (/^commit ($sha1_short)/o) {
681 my $cmt = $1;
682 if ($c && defined $c->{r} && $c->{r} != $r_last) {
683 $r_last = $c->{r};
684 process_commit($c, $r_min, $r_max, \@k) or
685 goto out;
686 }
687 $d = undef;
688 $c = { c => $cmt };
689 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
690 get_author_info($c, $1, $2, $3);
691 } elsif (/^(?:tree|parent|committer) /) {
692 # ignore
693 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
694 push @{$c->{raw}}, $_;
695 } elsif (/^diff /) {
696 $d = 1;
697 push @{$c->{diff}}, $_;
698 } elsif ($d) {
699 push @{$c->{diff}}, $_;
700 } elsif (/^ (git-svn-id:.+)$/) {
701 my ($url, $rev, $uuid) = extract_metadata($1);
702 $c->{r} = $rev;
703 } elsif (s/^ //) {
704 push @{$c->{l}}, $_;
705 }
706 }
707 if ($c && defined $c->{r} && $c->{r} != $r_last) {
708 $r_last = $c->{r};
709 process_commit($c, $r_min, $r_max, \@k);
710 }
711 if (@k) {
712 my $swap = $r_max;
713 $r_max = $r_min;
714 $r_min = $swap;
715 process_commit($_, $r_min, $r_max) foreach reverse @k;
716 }
717out:
718 close $log;
719 print '-' x72,"\n" unless $_incremental || $_oneline;
720}
721
3397f9df
EW
722########################### utility functions #########################
723
9d55b41a
EW
724sub rec_fetch {
725 my ($pfx, $p, @args) = @_;
726 my @dir;
727 foreach (sort <$p/*>) {
728 if (-r "$_/info/url") {
729 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
730 my $id = $pfx . basename $_;
731 next if $id eq 'trunk';
732 print "Fetching $id\n";
733 defined(my $pid = fork) or croak $!;
734 if (!$pid) {
735 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
736 init_vars();
737 fetch(@args);
738 exit 0;
739 }
740 waitpid $pid, 0;
741 croak $? if $?;
742 } elsif (-d $_) {
743 push @dir, $_;
744 }
745 }
746 foreach (@dir) {
747 my $x = $_;
748 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
749 rec_fetch($x, $_);
750 }
751}
752
753sub complete_url_ls_init {
754 my ($url, $var, $switch, $pfx) = @_;
755 unless ($var) {
756 print STDERR "W: $switch not specified\n";
757 return;
758 }
759 $var =~ s#/+$##;
760 if ($var !~ m#^[a-z\+]+://#) {
761 $var = '/' . $var if ($var !~ m#^/#);
762 unless ($url) {
763 print STDERR "E: '$var' is not a complete URL ",
764 "and a separate URL is not specified\n";
765 exit 1;
766 }
767 $var = $url . $var;
768 }
a5e0cedc
EW
769 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
770 : safe_qx(qw/svn ls --non-interactive/, $var));
9d55b41a
EW
771 my $old = $GIT_SVN;
772 defined(my $pid = fork) or croak $!;
773 if (!$pid) {
774 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
775 $u =~ s#/+$##;
776 if ($u !~ m!\Q$var\E/(.+)$!) {
777 print STDERR "W: Unrecognized URL: $u\n";
778 die "This should never happen\n";
779 }
780 my $id = $pfx.$1;
781 print "init $u => $id\n";
782 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
783 init_vars();
784 init($u);
785 }
786 exit 0;
787 }
788 waitpid $pid, 0;
789 croak $? if $?;
790}
791
792sub common_prefix {
793 my $paths = shift;
794 my %common;
795 foreach (@$paths) {
796 my @tmp = split m#/#, $_;
797 my $p = '';
798 while (my $x = shift @tmp) {
799 $p .= "/$x";
800 $common{$p} ||= 0;
801 $common{$p}++;
802 }
803 }
804 foreach (sort {length $b <=> length $a} keys %common) {
805 if ($common{$_} == @$paths) {
806 return $_;
807 }
808 }
809 return '';
810}
811
812# this isn't funky-filename safe, but good enough for now...
a5e0cedc 813sub graft_file_copy_cmd {
9d55b41a
EW
814 my ($grafts, $l_map, $u) = @_;
815 my $paths = $l_map->{$u};
816 my $pfx = common_prefix([keys %$paths]);
817
818 my $pid = open my $fh, '-|';
819 defined $pid or croak $!;
820 unless ($pid) {
a5e0cedc
EW
821 my @exec = qw/svn log -v/;
822 push @exec, "-r$_revision" if defined $_revision;
823 exec @exec, $u.$pfx or croak $!;
9d55b41a
EW
824 }
825 my ($r, $mp) = (undef, undef);
826 while (<$fh>) {
827 chomp;
828 if (/^\-{72}$/) {
829 $mp = $r = undef;
830 } elsif (/^r(\d+) \| /) {
831 $r = $1 unless defined $r;
832 } elsif (/^Changed paths:/) {
833 $mp = 1;
834 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
9d55b41a 835 my ($p1, $p0, $r0) = ($1, $2, $3);
a5e0cedc 836 my $c = find_graft_path_commit($paths, $p1, $r);
9d55b41a 837 next unless $c;
a5e0cedc 838 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
9d55b41a
EW
839 }
840 }
841}
842
a5e0cedc
EW
843sub graft_file_copy_lib {
844 my ($grafts, $l_map, $u) = @_;
845 my $tree_paths = $l_map->{$u};
846 my $pfx = common_prefix([keys %$tree_paths]);
847 my ($repo, $path) = repo_path_split($u.$pfx);
848 $SVN_LOG ||= libsvn_connect($repo);
849 $SVN ||= libsvn_connect($repo);
850
851 my ($base, $head) = libsvn_parse_revision();
852 my $inc = 1000;
853 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
854 while (1) {
855 my $pool = SVN::Pool->new;
856 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
857 sub {
858 libsvn_graft_file_copies($grafts, $tree_paths,
859 $path, @_);
860 }, $pool);
861 $pool->clear;
862 last if ($max >= $head);
863 $min = $max + 1;
864 $max += $inc;
865 $max = $head if ($max > $head);
866 }
867}
868
9d55b41a
EW
869sub process_merge_msg_matches {
870 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
871 my (@strong, @weak);
872 foreach (@matches) {
873 # merging with ourselves is not interesting
874 next if $_ eq $p;
875 if ($l_map->{$u}->{$_}) {
876 push @strong, $_;
877 } else {
878 push @weak, $_;
879 }
880 }
881 foreach my $w (@weak) {
882 last if @strong;
883 # no exact match, use branch name as regexp.
884 my $re = qr/\Q$w\E/i;
885 foreach (keys %{$l_map->{$u}}) {
886 if (/$re/) {
887 push @strong, $_;
888 last;
889 }
890 }
891 last if @strong;
892 $w = basename($w);
893 $re = qr/\Q$w\E/i;
894 foreach (keys %{$l_map->{$u}}) {
895 if (/$re/) {
896 push @strong, $_;
897 last;
898 }
899 }
900 }
901 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
902 \s(?:[a-f\d\-]+)$/xsm);
903 unless (defined $rev) {
904 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
905 \@(?:[a-f\d\-]+)/xsm);
906 return unless defined $rev;
907 }
908 foreach my $m (@strong) {
909 my ($r0, $s0) = find_rev_before($rev, $m);
910 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
911 }
912}
913
914sub graft_merge_msg {
915 my ($grafts, $l_map, $u, $p, @re) = @_;
916
917 my $x = $l_map->{$u}->{$p};
918 my $rl = rev_list_raw($x);
919 while (my $c = next_rev_list_entry($rl)) {
920 foreach my $re (@re) {
921 my (@br) = ($c->{m} =~ /$re/g);
922 next unless @br;
923 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
924 }
925 }
926}
927
1d52aba8
EW
928sub read_uuid {
929 return if $SVN_UUID;
a5e0cedc
EW
930 if ($_use_lib) {
931 my $pool = SVN::Pool->new;
932 $SVN_UUID = $SVN->get_uuid($pool);
933 $pool->clear;
934 } else {
935 my $info = shift || svn_info('.');
936 $SVN_UUID = $info->{'Repository UUID'} or
1d52aba8 937 croak "Repository UUID unreadable\n";
a5e0cedc 938 }
883d0a78
EW
939 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
940}
941
942sub quiet_run {
943 my $pid = fork;
944 defined $pid or croak $!;
945 if (!$pid) {
946 open my $null, '>', '/dev/null' or croak $!;
947 open STDERR, '>&', $null or croak $!;
948 open STDOUT, '>&', $null or croak $!;
949 exec @_ or croak $!;
950 }
951 waitpid $pid, 0;
952 return $?;
953}
954
955sub repo_path_split {
956 my $full_url = shift;
957 $full_url =~ s#/+$##;
958
959 foreach (@repo_path_split_cache) {
960 if ($full_url =~ s#$_##) {
961 my $u = $1;
962 $full_url =~ s#^/+##;
963 return ($u, $full_url);
964 }
965 }
966
967 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
968 $path =~ s#^/+##;
969 my @paths = split(m#/+#, $path);
970
a5e0cedc
EW
971 if ($_use_lib) {
972 while (1) {
973 $SVN = libsvn_connect($url);
974 last if (defined $SVN &&
975 defined eval { $SVN->get_latest_revnum });
976 my $n = shift @paths || last;
977 $url .= "/$n";
978 }
979 } else {
980 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
981 my $n = shift @paths || last;
982 $url .= "/$n";
983 }
883d0a78
EW
984 }
985 push @repo_path_split_cache, qr/^(\Q$url\E)/;
9d55b41a 986 $path = join('/',@paths);
883d0a78 987 return ($url, $path);
1d52aba8
EW
988}
989
3397f9df
EW
990sub setup_git_svn {
991 defined $SVN_URL or croak "SVN repository location required\n";
992 unless (-d $GIT_DIR) {
993 croak "GIT_DIR=$GIT_DIR does not exist!\n";
994 }
883d0a78
EW
995 mkpath([$GIT_SVN_DIR]);
996 mkpath(["$GIT_SVN_DIR/info"]);
3397f9df 997 mkpath([$REV_DIR]);
883d0a78 998 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
3397f9df 999
883d0a78 1000 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
3397f9df
EW
1001 print $fd '.svn',"\n";
1002 close $fd or croak $!;
883d0a78
EW
1003 my ($url, $path) = repo_path_split($SVN_URL);
1004 s_to_file($url, "$GIT_SVN_DIR/info/repo_url");
1005 s_to_file($path, "$GIT_SVN_DIR/info/repo_path");
3397f9df
EW
1006}
1007
1008sub assert_svn_wc_clean {
a5e0cedc 1009 return if $_use_lib;
36f5b1f0 1010 my ($svn_rev) = @_;
3397f9df 1011 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
ce4c8b24
EW
1012 my $lcr = svn_info('.')->{'Last Changed Rev'};
1013 if ($svn_rev != $lcr) {
1014 print STDERR "Checking for copy-tree ... ";
ce4c8b24
EW
1015 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1016 "-r$lcr:$svn_rev")));
1017 if (@diff) {
1018 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1019 } else {
1020 print STDERR "OK!\n";
1021 }
3397f9df
EW
1022 }
1023 my @status = grep(!/^Performing status on external/,(`svn status`));
1024 @status = grep(!/^\s*$/,@status);
1025 if (scalar @status) {
1026 print STDERR "Tree ($SVN_WC) is not clean:\n";
1027 print STDERR $_ foreach @status;
1028 croak;
1029 }
cf52b8f0
EW
1030}
1031
a5e0cedc 1032sub get_tree_from_treeish {
cf52b8f0
EW
1033 my ($treeish) = @_;
1034 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1035 chomp(my $type = `git-cat-file -t $treeish`);
1036 my $expected;
1037 while ($type eq 'tag') {
1038 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1039 }
1040 if ($type eq 'commit') {
1041 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1042 ($expected) = ($expected =~ /^tree ($sha1)$/);
1043 die "Unable to get tree from $treeish\n" unless $expected;
1044 } elsif ($type eq 'tree') {
1045 $expected = $treeish;
1046 } else {
1047 die "$treeish is a $type, expected tree, tag or commit\n";
1048 }
a5e0cedc
EW
1049 return $expected;
1050}
1051
1052sub assert_tree {
1053 return if $_use_lib;
1054 my ($treeish) = @_;
1055 my $expected = get_tree_from_treeish($treeish);
cf52b8f0 1056
cf52b8f0
EW
1057 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1058 if (-e $tmpindex) {
1059 unlink $tmpindex or croak $!;
1060 }
a5e0cedc 1061 my $old_index = set_index($tmpindex);
36f5b1f0 1062 index_changes(1);
cf52b8f0 1063 chomp(my $tree = `git-write-tree`);
a5e0cedc 1064 restore_index($old_index);
cf52b8f0
EW
1065 if ($tree ne $expected) {
1066 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
3397f9df 1067 }
36f5b1f0 1068 unlink $tmpindex;
3397f9df
EW
1069}
1070
1071sub parse_diff_tree {
1072 my $diff_fh = shift;
1073 local $/ = "\0";
1074 my $state = 'meta';
1075 my @mods;
1076 while (<$diff_fh>) {
1077 chomp $_; # this gets rid of the trailing "\0"
3397f9df
EW
1078 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1079 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1080 push @mods, { mode_a => $1, mode_b => $2,
1081 sha1_b => $3, chg => $4 };
1082 if ($4 =~ /^(?:C|R)$/) {
1083 $state = 'file_a';
1084 } else {
1085 $state = 'file_b';
1086 }
1087 } elsif ($state eq 'file_a') {
cf52b8f0 1088 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1089 if ($x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1090 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1091 }
1092 $x->{file_a} = $_;
1093 $state = 'file_b';
1094 } elsif ($state eq 'file_b') {
cf52b8f0 1095 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1096 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1097 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1098 }
1099 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
cf52b8f0 1100 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1101 }
1102 $x->{file_b} = $_;
1103 $state = 'meta';
1104 } else {
cf52b8f0 1105 croak "Error parsing $_\n";
3397f9df
EW
1106 }
1107 }
1108 close $diff_fh or croak $!;
cf52b8f0 1109
3397f9df
EW
1110 return \@mods;
1111}
1112
1113sub svn_check_prop_executable {
1114 my $m = shift;
cf52b8f0
EW
1115 return if -l $m->{file_b};
1116 if ($m->{mode_b} =~ /755$/) {
1117 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1118 if ($m->{mode_a} !~ /755$/) {
1119 sys(qw(svn propset svn:executable 1), $m->{file_b});
1120 }
1121 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
3397f9df
EW
1122 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1123 sys(qw(svn propdel svn:executable), $m->{file_b});
cf52b8f0
EW
1124 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1125 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
3397f9df
EW
1126 }
1127}
1128
1129sub svn_ensure_parent_path {
1130 my $dir_b = dirname(shift);
1131 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1132 mkpath([$dir_b]) unless (-d $dir_b);
1133 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1134}
1135
cf52b8f0
EW
1136sub precommit_check {
1137 my $mods = shift;
1138 my (%rm_file, %rmdir_check, %added_check);
1139
1140 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1141 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1142 if ($m->{chg} eq 'R') {
1143 if (-d $m->{file_b}) {
1144 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1145 }
1146 # dir/$file => dir/file/$file
1147 my $dirname = dirname($m->{file_b});
1148 while ($dirname ne File::Spec->curdir) {
1149 if ($dirname ne $m->{file_a}) {
1150 $dirname = dirname($dirname);
1151 next;
1152 }
1153 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1154 }
1155 # baz/zzz => baz (baz is a file)
1156 $dirname = dirname($m->{file_a});
1157 while ($dirname ne File::Spec->curdir) {
1158 if ($dirname ne $m->{file_b}) {
1159 $dirname = dirname($dirname);
1160 next;
1161 }
1162 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1163 }
1164 }
1165 if ($m->{chg} =~ /^(D|R)$/) {
1166 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1167 $rm_file{ $m->{$t} } = 1;
1168 my $dirname = dirname( $m->{$t} );
1169 my $basename = basename( $m->{$t} );
1170 $rmdir_check{$dirname}->{$basename} = 1;
1171 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1172 if (-d $m->{file_b}) {
1173 err_dir_to_file($m->{file_b});
1174 }
1175 my $dirname = dirname( $m->{file_b} );
1176 my $basename = basename( $m->{file_b} );
1177 $added_check{$dirname}->{$basename} = 1;
1178 while ($dirname ne File::Spec->curdir) {
1179 if ($rm_file{$dirname}) {
1180 err_file_to_dir($m->{file_b});
1181 }
1182 $dirname = dirname $dirname;
1183 }
1184 }
1185 }
1186 return (\%rmdir_check, \%added_check);
1187
1188 sub err_dir_to_file {
1189 my $file = shift;
1190 print STDERR "Node change from directory to file ",
1191 "is not supported by Subversion: ",$file,"\n";
1192 exit 1;
1193 }
1194 sub err_file_to_dir {
1195 my $file = shift;
1196 print STDERR "Node change from file to directory ",
1197 "is not supported by Subversion: ",$file,"\n";
1198 exit 1;
1199 }
1200}
1201
a5e0cedc
EW
1202
1203sub get_diff {
cf52b8f0 1204 my ($svn_rev, $treeish) = @_;
3397f9df 1205 my $from = file_to_s("$REV_DIR/$svn_rev");
36f5b1f0 1206 assert_tree($from);
ac8e0b91 1207 print "diff-tree $from $treeish\n";
3397f9df
EW
1208 my $pid = open my $diff_fh, '-|';
1209 defined $pid or croak $!;
1210 if ($pid == 0) {
162f4129
EW
1211 my @diff_tree = qw(git-diff-tree -z -r);
1212 if ($_cp_similarity) {
1213 push @diff_tree, "-C$_cp_similarity";
1214 } else {
1215 push @diff_tree, '-C';
1216 }
72942938
EW
1217 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1218 push @diff_tree, "-l$_l" if defined $_l;
cf52b8f0 1219 exec(@diff_tree, $from, $treeish) or croak $!;
3397f9df 1220 }
a5e0cedc
EW
1221 return parse_diff_tree($diff_fh);
1222}
1223
1224sub svn_checkout_tree {
1225 my ($svn_rev, $treeish) = @_;
1226 my $mods = get_diff($svn_rev, $treeish);
1227 return $mods unless (scalar @$mods);
cf52b8f0
EW
1228 my ($rm, $add) = precommit_check($mods);
1229
1230 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1231 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3397f9df
EW
1232 if ($m->{chg} eq 'C') {
1233 svn_ensure_parent_path( $m->{file_b} );
1234 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
cf52b8f0 1235 apply_mod_line_blob($m);
3397f9df
EW
1236 svn_check_prop_executable($m);
1237 } elsif ($m->{chg} eq 'D') {
3397f9df
EW
1238 sys(qw(svn rm --force), $m->{file_b});
1239 } elsif ($m->{chg} eq 'R') {
1240 svn_ensure_parent_path( $m->{file_b} );
1241 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
cf52b8f0 1242 apply_mod_line_blob($m);
3397f9df 1243 svn_check_prop_executable($m);
3397f9df 1244 } elsif ($m->{chg} eq 'M') {
cf52b8f0 1245 apply_mod_line_blob($m);
3397f9df
EW
1246 svn_check_prop_executable($m);
1247 } elsif ($m->{chg} eq 'T') {
1248 sys(qw(svn rm --force),$m->{file_b});
cf52b8f0 1249 apply_mod_line_blob($m);
3397f9df 1250 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 1251 svn_check_prop_executable($m);
3397f9df
EW
1252 } elsif ($m->{chg} eq 'A') {
1253 svn_ensure_parent_path( $m->{file_b} );
cf52b8f0 1254 apply_mod_line_blob($m);
3397f9df 1255 sys(qw(svn add --force), $m->{file_b});
cf52b8f0 1256 svn_check_prop_executable($m);
3397f9df
EW
1257 } else {
1258 croak "Invalid chg: $m->{chg}\n";
1259 }
1260 }
cf52b8f0
EW
1261
1262 assert_tree($treeish);
1263 if ($_rmdir) { # remove empty directories
1264 handle_rmdir($rm, $add);
1265 }
1266 assert_tree($treeish);
1267 return $mods;
1268}
1269
a5e0cedc
EW
1270sub libsvn_checkout_tree {
1271 my ($svn_rev, $treeish, $ed) = @_;
1272 my $mods = get_diff($svn_rev, $treeish);
1273 return $mods unless (scalar @$mods);
1274 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1275 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1276 my $f = $m->{chg};
1277 if (defined $o{$f}) {
1278 $ed->$f($m);
1279 } else {
1280 croak "Invalid change type: $f\n";
1281 }
1282 }
1283 $ed->rmdirs if $_rmdir;
1284 return $mods;
1285}
1286
cf52b8f0
EW
1287# svn ls doesn't work with respect to the current working tree, but what's
1288# in the repository. There's not even an option for it... *sigh*
1289# (added files don't show up and removed files remain in the ls listing)
1290sub svn_ls_current {
1291 my ($dir, $rm, $add) = @_;
1292 chomp(my @ls = safe_qx('svn','ls',$dir));
1293 my @ret = ();
1294 foreach (@ls) {
1295 s#/$##; # trailing slashes are evil
1296 push @ret, $_ unless $rm->{$dir}->{$_};
1297 }
1298 if (exists $add->{$dir}) {
1299 push @ret, keys %{$add->{$dir}};
1300 }
1301 return \@ret;
1302}
1303
1304sub handle_rmdir {
1305 my ($rm, $add) = @_;
1306
1307 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1308 my $ls = svn_ls_current($dir, $rm, $add);
1309 next if (scalar @$ls);
1310 sys(qw(svn rm --force),$dir);
1311
1312 my $dn = dirname $dir;
1313 $rm->{ $dn }->{ basename $dir } = 1;
1314 $ls = svn_ls_current($dn, $rm, $add);
1315 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1316 sys(qw(svn rm --force),$dn);
1317 $dir = basename $dn;
1318 $dn = dirname $dn;
1319 $rm->{ $dn }->{ $dir } = 1;
1320 $ls = svn_ls_current($dn, $rm, $add);
3397f9df
EW
1321 }
1322 }
1323}
1324
a5e0cedc
EW
1325sub get_commit_message {
1326 my ($commit, $commit_msg) = (@_);
e17512f3 1327 my %log_msg = ( msg => '' );
ac8e0b91 1328 open my $msg, '>', $commit_msg or croak $!;
3397f9df 1329
a5e0cedc 1330 print "commit: $commit\n";
3397f9df
EW
1331 chomp(my $type = `git-cat-file -t $commit`);
1332 if ($type eq 'commit') {
1333 my $pid = open my $msg_fh, '-|';
1334 defined $pid or croak $!;
1335
1336 if ($pid == 0) {
1337 exec(qw(git-cat-file commit), $commit) or croak $!;
1338 }
1339 my $in_msg = 0;
1340 while (<$msg_fh>) {
1341 if (!$in_msg) {
1342 $in_msg = 1 if (/^\s*$/);
df746c5a
EW
1343 } elsif (/^git-svn-id: /) {
1344 # skip this, we regenerate the correct one
1345 # on re-fetch anyways
3397f9df
EW
1346 } else {
1347 print $msg $_ or croak $!;
1348 }
1349 }
1350 close $msg_fh or croak $!;
1351 }
1352 close $msg or croak $!;
1353
1354 if ($_edit || ($type eq 'tree')) {
1355 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1356 system($editor, $commit_msg);
1357 }
ac8e0b91
EW
1358
1359 # file_to_s removes all trailing newlines, so just use chomp() here:
1360 open $msg, '<', $commit_msg or croak $!;
1361 { local $/; chomp($log_msg{msg} = <$msg>); }
1362 close $msg or croak $!;
1363
a5e0cedc
EW
1364 return \%log_msg;
1365}
1366
1367sub svn_commit_tree {
1368 my ($svn_rev, $commit) = @_;
1369 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1370 my $log_msg = get_commit_message($commit, $commit_msg);
1371 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
ac8e0b91
EW
1372 print "Committing $commit: $oneline\n";
1373
ce475dfc
EW
1374 if (defined $LC_ALL) {
1375 $ENV{LC_ALL} = $LC_ALL;
1376 } else {
1377 delete $ENV{LC_ALL};
1378 }
3397f9df 1379 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
ce475dfc 1380 $ENV{LC_ALL} = 'C';
3397f9df 1381 unlink $commit_msg;
ce475dfc
EW
1382 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1383 if (!defined $committed) {
1384 my $out = join("\n",@ci_output);
1385 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1386 $out, "\n\nAssuming English locale...";
1387 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1388 defined $committed or die " FAILED!\n",
3397f9df 1389 "Commit output failed to parse committed revision!\n",
ce475dfc
EW
1390 print STDERR " OK\n";
1391 }
3397f9df 1392
e17512f3 1393 my @svn_up = qw(svn up);
3397f9df 1394 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
ce475dfc
EW
1395 if ($committed == ($svn_rev + 1)) {
1396 push @svn_up, "-r$committed";
e17512f3
EW
1397 sys(@svn_up);
1398 my $info = svn_info('.');
1399 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
ce475dfc
EW
1400 if ($info->{'Last Changed Rev'} != $committed) {
1401 croak "$info->{'Last Changed Rev'} != $committed\n"
e17512f3
EW
1402 }
1403 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1404 /(\d{4})\-(\d\d)\-(\d\d)\s
1405 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1406 or croak "Failed to parse date: $date\n";
a5e0cedc
EW
1407 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1408 $log_msg->{author} = $info->{'Last Changed Author'};
1409 $log_msg->{revision} = $committed;
1410 $log_msg->{msg} .= "\n";
e17512f3 1411 my $parent = file_to_s("$REV_DIR/$svn_rev");
a5e0cedc 1412 git_commit($log_msg, $parent, $commit);
ce475dfc 1413 return $committed;
e17512f3
EW
1414 }
1415 # resync immediately
1416 push @svn_up, "-r$svn_rev";
3397f9df 1417 sys(@svn_up);
ce475dfc 1418 return fetch("$committed=$commit")->{revision};
3397f9df
EW
1419}
1420
9d55b41a
EW
1421sub rev_list_raw {
1422 my (@args) = @_;
1423 my $pid = open my $fh, '-|';
1424 defined $pid or croak $!;
1425 if (!$pid) {
1426 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1427 }
1428 return { fh => $fh, t => { } };
1429}
1430
1431sub next_rev_list_entry {
1432 my $rl = shift;
1433 my $fh = $rl->{fh};
1434 my $x = $rl->{t};
1435 while (<$fh>) {
1436 if (/^commit ($sha1)$/o) {
1437 if ($x->{c}) {
1438 $rl->{t} = { c => $1 };
1439 return $x;
1440 } else {
1441 $x->{c} = $1;
1442 }
1443 } elsif (/^parent ($sha1)$/o) {
1444 $x->{p}->{$1} = 1;
1445 } elsif (s/^ //) {
1446 $x->{m} ||= '';
1447 $x->{m} .= $_;
1448 }
1449 }
1450 return ($x != $rl->{t}) ? $x : undef;
1451}
1452
03823184
EW
1453# read the entire log into a temporary file (which is removed ASAP)
1454# and store the file handle + parser state
3397f9df
EW
1455sub svn_log_raw {
1456 my (@log_args) = @_;
03823184
EW
1457 my $log_fh = IO::File->new_tmpfile or croak $!;
1458 my $pid = fork;
3397f9df 1459 defined $pid or croak $!;
03823184
EW
1460 if (!$pid) {
1461 open STDOUT, '>&', $log_fh or croak $!;
3397f9df
EW
1462 exec (qw(svn log), @log_args) or croak $!
1463 }
03823184 1464 waitpid $pid, 0;
b8c92cad 1465 croak $? if $?;
03823184
EW
1466 seek $log_fh, 0, 0 or croak $!;
1467 return { state => 'sep', fh => $log_fh };
1468}
1469
1470sub next_log_entry {
1471 my $log = shift; # retval of svn_log_raw()
1472 my $ret = undef;
1473 my $fh = $log->{fh};
3397f9df 1474
03823184 1475 while (<$fh>) {
3397f9df
EW
1476 chomp;
1477 if (/^\-{72}$/) {
03823184
EW
1478 if ($log->{state} eq 'msg') {
1479 if ($ret->{lines}) {
1480 $ret->{msg} .= $_."\n";
1481 unless(--$ret->{lines}) {
1482 $log->{state} = 'sep';
ce6f3519
EW
1483 }
1484 } else {
1485 croak "Log parse error at: $_\n",
03823184 1486 $ret->{revision},
ce6f3519
EW
1487 "\n";
1488 }
1489 next;
1490 }
03823184 1491 if ($log->{state} ne 'sep') {
ce6f3519 1492 croak "Log parse error at: $_\n",
03823184
EW
1493 "state: $log->{state}\n",
1494 $ret->{revision},
ce6f3519
EW
1495 "\n";
1496 }
03823184 1497 $log->{state} = 'rev';
3397f9df
EW
1498
1499 # if we have an empty log message, put something there:
03823184
EW
1500 if ($ret) {
1501 $ret->{msg} ||= "\n";
1502 delete $ret->{lines};
1503 return $ret;
3397f9df
EW
1504 }
1505 next;
1506 }
03823184 1507 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
3397f9df 1508 my $rev = $1;
ce6f3519
EW
1509 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1510 ($lines) = ($lines =~ /(\d+)/);
3397f9df
EW
1511 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1512 /(\d{4})\-(\d\d)\-(\d\d)\s
1513 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1514 or croak "Failed to parse date: $date\n";
03823184 1515 $ret = { revision => $rev,
3397f9df
EW
1516 date => "$tz $Y-$m-$d $H:$M:$S",
1517 author => $author,
ce6f3519 1518 lines => $lines,
03823184 1519 msg => '' };
a9612be2
EW
1520 if (defined $_authors && ! defined $users{$author}) {
1521 die "Author: $author not defined in ",
1522 "$_authors file\n";
1523 }
03823184 1524 $log->{state} = 'msg_start';
3397f9df
EW
1525 next;
1526 }
1527 # skip the first blank line of the message:
03823184
EW
1528 if ($log->{state} eq 'msg_start' && /^$/) {
1529 $log->{state} = 'msg';
1530 } elsif ($log->{state} eq 'msg') {
1531 if ($ret->{lines}) {
1532 $ret->{msg} .= $_."\n";
1533 unless (--$ret->{lines}) {
1534 $log->{state} = 'sep';
ce6f3519
EW
1535 }
1536 } else {
1537 croak "Log parse error at: $_\n",
03823184 1538 $ret->{revision},"\n";
ce6f3519 1539 }
3397f9df
EW
1540 }
1541 }
03823184 1542 return $ret;
3397f9df
EW
1543}
1544
1545sub svn_info {
1546 my $url = shift || $SVN_URL;
1547
1548 my $pid = open my $info_fh, '-|';
1549 defined $pid or croak $!;
1550
1551 if ($pid == 0) {
1552 exec(qw(svn info),$url) or croak $!;
1553 }
1554
1555 my $ret = {};
1556 # only single-lines seem to exist in svn info output
1557 while (<$info_fh>) {
1558 chomp $_;
e17512f3 1559 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
3397f9df
EW
1560 $ret->{$1} = $2;
1561 push @{$ret->{-order}}, $1;
1562 }
1563 }
1564 close $info_fh or croak $!;
1565 return $ret;
1566}
1567
1568sub sys { system(@_) == 0 or croak $? }
1569
36f5b1f0
EW
1570sub eol_cp {
1571 my ($from, $to) = @_;
8a97e368 1572 my $es = svn_propget_base('svn:eol-style', $to);
36f5b1f0
EW
1573 open my $rfd, '<', $from or croak $!;
1574 binmode $rfd or croak $!;
1575 open my $wfd, '>', $to or croak $!;
1576 binmode $wfd or croak $!;
a5e0cedc
EW
1577 eol_cp_fd($rfd, $wfd, $es);
1578 close $rfd or croak $!;
1579 close $wfd or croak $!;
1580}
36f5b1f0 1581
a5e0cedc
EW
1582sub eol_cp_fd {
1583 my ($rfd, $wfd, $es) = @_;
1584 my $eol = defined $es ? $EOL{$es} : undef;
36f5b1f0 1585 my $buf;
4a393f2b 1586 use bytes;
36f5b1f0
EW
1587 while (1) {
1588 my ($r, $w, $t);
1589 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1590 return unless $r;
4a393f2b
EW
1591 if ($eol) {
1592 if ($buf =~ /\015$/) {
1593 my $c;
1594 defined($r = sysread($rfd,$c,1)) or croak $!;
1595 $buf .= $c if $r > 0;
1596 }
1597 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1598 $r = length($buf);
1599 }
36f5b1f0
EW
1600 for ($w = 0; $w < $r; $w += $t) {
1601 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1602 }
1603 }
4a393f2b 1604 no bytes;
36f5b1f0
EW
1605}
1606
1607sub do_update_index {
1608 my ($z_cmd, $cmd, $no_text_base) = @_;
1609
1610 my $z = open my $p, '-|';
1611 defined $z or croak $!;
1612 unless ($z) { exec @$z_cmd or croak $! }
1613
1614 my $pid = open my $ui, '|-';
1615 defined $pid or croak $!;
1616 unless ($pid) {
1617 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1618 }
1619 local $/ = "\0";
1620 while (my $x = <$p>) {
1621 chomp $x;
1622 if (!$no_text_base && lstat $x && ! -l _ &&
8a97e368 1623 svn_propget_base('svn:keywords', $x)) {
36f5b1f0
EW
1624 my $mode = -x _ ? 0755 : 0644;
1625 my ($v,$d,$f) = File::Spec->splitpath($x);
1626 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1627 'text-base',"$f.svn-base");
1628 $tb =~ s#^/##;
1629 unless (-f $tb) {
1630 $tb = File::Spec->catfile($d, '.svn',
1631 'text-base',"$f.svn-base");
1632 $tb =~ s#^/##;
1633 }
1634 unlink $x or croak $!;
1635 eol_cp($tb, $x);
1636 chmod(($mode &~ umask), $x) or croak $!;
1637 }
1638 print $ui $x,"\0";
1639 }
1640 close $ui or croak $!;
1641}
1642
1643sub index_changes {
a5e0cedc 1644 return if $_use_lib;
36f5b1f0
EW
1645 my $no_text_base = shift;
1646 do_update_index([qw/git-diff-files --name-only -z/],
1647 'remove',
1648 $no_text_base);
1649 do_update_index([qw/git-ls-files -z --others/,
883d0a78 1650 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
36f5b1f0
EW
1651 'add',
1652 $no_text_base);
3397f9df
EW
1653}
1654
1655sub s_to_file {
1656 my ($str, $file, $mode) = @_;
1657 open my $fd,'>',$file or croak $!;
1658 print $fd $str,"\n" or croak $!;
1659 close $fd or croak $!;
1660 chmod ($mode &~ umask, $file) if (defined $mode);
1661}
1662
1663sub file_to_s {
1664 my $file = shift;
1665 open my $fd,'<',$file or croak "$!: file: $file\n";
1666 local $/;
1667 my $ret = <$fd>;
1668 close $fd or croak $!;
1669 $ret =~ s/\s*$//s;
1670 return $ret;
1671}
1672
1673sub assert_revision_unknown {
1674 my $revno = shift;
1675 if (-f "$REV_DIR/$revno") {
1676 croak "$REV_DIR/$revno already exists! ",
1677 "Why are we refetching it?";
1678 }
1679}
1680
ac749050
EW
1681sub trees_eq {
1682 my ($x, $y) = @_;
1683 my @x = safe_qx('git-cat-file','commit',$x);
1684 my @y = safe_qx('git-cat-file','commit',$y);
1685 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1686 || $y[0] !~ /^tree $sha1\n$/) {
1687 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1688 return 0
1689 }
1690 return 1;
1691}
1692
3397f9df
EW
1693sub assert_revision_eq_or_unknown {
1694 my ($revno, $commit) = @_;
1695 if (-f "$REV_DIR/$revno") {
1696 my $current = file_to_s("$REV_DIR/$revno");
ac749050 1697 if (($commit ne $current) && !trees_eq($commit, $current)) {
3397f9df
EW
1698 croak "$REV_DIR/$revno already exists!\n",
1699 "current: $current\nexpected: $commit\n";
1700 }
1701 return;
1702 }
1703}
1704
1705sub git_commit {
1706 my ($log_msg, @parents) = @_;
1707 assert_revision_unknown($log_msg->{revision});
69f0d91e
EW
1708 map_tree_joins() if (@_branch_from && !%tree_map);
1709
a5e0cedc
EW
1710 my (@tmp_parents, @exec_parents, %seen_parent);
1711 if (my $lparents = $log_msg->{parents}) {
1712 @tmp_parents = @$lparents
1713 }
3397f9df
EW
1714 # commit parents can be conditionally bound to a particular
1715 # svn revision via: "svn_revno=commit_sha1", filter them out here:
3397f9df
EW
1716 foreach my $p (@parents) {
1717 next unless defined $p;
1718 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1719 if ($1 == $log_msg->{revision}) {
a5e0cedc 1720 push @tmp_parents, $2;
3397f9df
EW
1721 }
1722 } else {
a5e0cedc 1723 push @tmp_parents, $p if $p =~ /$sha1_short/o;
3397f9df
EW
1724 }
1725 }
a5e0cedc
EW
1726 my $tree = $log_msg->{tree};
1727 if (!defined $tree) {
1728 my $index = set_index($GIT_SVN_INDEX);
36f5b1f0 1729 index_changes();
a5e0cedc 1730 chomp($tree = `git-write-tree`);
b8c92cad 1731 croak $? if $?;
a5e0cedc
EW
1732 restore_index($index);
1733 }
1734 if (exists $tree_map{$tree}) {
1735 push @tmp_parents, @{$tree_map{$tree}};
1736 }
1737 foreach (@tmp_parents) {
1738 next if $seen_parent{$_};
1739 $seen_parent{$_} = 1;
1740 push @exec_parents, $_;
1741 # MAXPARENT is defined to 16 in commit-tree.c:
1742 last if @exec_parents > 16;
1743 }
1744
1745 defined(my $pid = open my $out_fh, '-|') or croak $!;
1746 if ($pid == 0) {
3397f9df
EW
1747 my $msg_fh = IO::File->new_tmpfile or croak $!;
1748 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1749 "$SVN_URL\@$log_msg->{revision}",
1ca72aef 1750 " $SVN_UUID\n" or croak $!;
3397f9df
EW
1751 $msg_fh->flush == 0 or croak $!;
1752 seek $msg_fh, 0, 0 or croak $!;
1ca72aef 1753 set_commit_env($log_msg);
3397f9df
EW
1754 my @exec = ('git-commit-tree',$tree);
1755 push @exec, '-p', $_ foreach @exec_parents;
1756 open STDIN, '<&', $msg_fh or croak $!;
3397f9df
EW
1757 exec @exec or croak $!;
1758 }
3397f9df 1759 chomp(my $commit = do { local $/; <$out_fh> });
a5e0cedc 1760 close $out_fh or croak $?;
3397f9df
EW
1761 if ($commit !~ /^$sha1$/o) {
1762 croak "Failed to commit, invalid sha1: $commit\n";
1763 }
2beb3cdd 1764 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
3397f9df 1765 if (my $primary_parent = shift @exec_parents) {
1d52aba8
EW
1766 $pid = fork;
1767 defined $pid or croak $!;
1768 if (!$pid) {
1769 close STDERR;
1770 close STDOUT;
1771 exec 'git-rev-parse','--verify',
b8c92cad 1772 "refs/remotes/$GIT_SVN^0" or croak $!;
1d52aba8
EW
1773 }
1774 waitpid $pid, 0;
1775 push @update_ref, $primary_parent unless $?;
3397f9df
EW
1776 }
1777 sys(@update_ref);
883d0a78 1778 sys('git-update-ref',"svn/$GIT_SVN/revs/$log_msg->{revision}",$commit);
a5e0cedc 1779 # this output is read via pipe, do not change:
3397f9df 1780 print "r$log_msg->{revision} = $commit\n";
dc5869c0
EW
1781 if ($_repack && (--$_repack_nr == 0)) {
1782 $_repack_nr = $_repack;
1783 sys("git repack $_repack_flags");
1784 }
3397f9df
EW
1785 return $commit;
1786}
1787
a9612be2 1788sub set_commit_env {
1ca72aef 1789 my ($log_msg) = @_;
a9612be2 1790 my $author = $log_msg->{author};
a5e0cedc
EW
1791 if (!defined $author || length $author == 0) {
1792 $author = '(no author)';
1793 }
a9612be2 1794 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1ca72aef 1795 : ($author,"$author\@$SVN_UUID");
a9612be2
EW
1796 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1797 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1798 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1799}
1800
cf52b8f0
EW
1801sub apply_mod_line_blob {
1802 my $m = shift;
1803 if ($m->{mode_b} =~ /^120/) {
1804 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1805 } else {
1806 blob_to_file($m->{sha1_b}, $m->{file_b});
1807 }
1808}
1809
3397f9df
EW
1810sub blob_to_symlink {
1811 my ($blob, $link) = @_;
1812 defined $link or croak "\$link not defined!\n";
1813 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
1814 if (-l $link || -f _) {
1815 unlink $link or croak $!;
1816 }
1817
3397f9df
EW
1818 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1819 symlink $dest, $link or croak $!;
1820}
1821
1822sub blob_to_file {
1823 my ($blob, $file) = @_;
1824 defined $file or croak "\$file not defined!\n";
1825 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
1826 if (-l $file || -f _) {
1827 unlink $file or croak $!;
1828 }
1829
3397f9df
EW
1830 open my $blob_fh, '>', $file or croak "$!: $file\n";
1831 my $pid = fork;
1832 defined $pid or croak $!;
1833
1834 if ($pid == 0) {
1835 open STDOUT, '>&', $blob_fh or croak $!;
b8c92cad 1836 exec('git-cat-file','blob',$blob) or croak $!;
3397f9df
EW
1837 }
1838 waitpid $pid, 0;
1839 croak $? if $?;
1840
1841 close $blob_fh or croak $!;
1842}
1843
1844sub safe_qx {
1845 my $pid = open my $child, '-|';
1846 defined $pid or croak $!;
1847 if ($pid == 0) {
b8c92cad 1848 exec(@_) or croak $!;
3397f9df
EW
1849 }
1850 my @ret = (<$child>);
1851 close $child or croak $?;
1852 die $? if $?; # just in case close didn't error out
1853 return wantarray ? @ret : join('',@ret);
1854}
1855
1d52aba8
EW
1856sub svn_compat_check {
1857 my @co_help = safe_qx(qw(svn co -h));
1858 unless (grep /ignore-externals/,@co_help) {
3397f9df
EW
1859 print STDERR "W: Installed svn version does not support ",
1860 "--ignore-externals\n";
1861 $_no_ignore_ext = 1;
1862 }
1d52aba8
EW
1863 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1864 $_svn_co_url_revs = 1;
1865 }
8a97e368
EW
1866 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1867 $_svn_pg_peg_revs = 1;
1868 }
7317ed90
EW
1869
1870 # I really, really hope nobody hits this...
1871 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1872 print STDERR <<'';
1873W: The installed svn version does not support the --stop-on-copy flag in
1874 the log command.
1875 Lets hope the directory you're tracking is not a branch or tag
1876 and was never moved within the repository...
1877
1878 $_no_stop_copy = 1;
1879 }
1d52aba8
EW
1880}
1881
1882# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1883# (and they won't honor URL@<rev> without -r<rev>, too!)
1884sub svn_cmd_checkout {
1885 my ($url, $rev, $dir) = @_;
1886 my @cmd = ('svn','co', "-r$rev");
1887 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1888 $url .= "\@$rev" if $_svn_co_url_revs;
1889 sys(@cmd, $url, $dir);
3397f9df 1890}
2beb3cdd
EW
1891
1892sub check_upgrade_needed {
1893 my $old = eval {
1894 my $pid = open my $child, '-|';
1895 defined $pid or croak $!;
1896 if ($pid == 0) {
1897 close STDERR;
b8c92cad 1898 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2beb3cdd
EW
1899 }
1900 my @ret = (<$child>);
1901 close $child or croak $?;
1902 die $? if $?; # just in case close didn't error out
1903 return wantarray ? @ret : join('',@ret);
1904 };
1905 return unless $old;
1906 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1907 if ($@ || !$head) {
1908 print STDERR "Please run: $0 rebuild --upgrade\n";
1909 exit 1;
1910 }
1911}
1912
69f0d91e
EW
1913# fills %tree_map with a reverse mapping of trees to commits. Useful
1914# for finding parents to commit on.
1915sub map_tree_joins {
098749d9 1916 my %seen;
69f0d91e
EW
1917 foreach my $br (@_branch_from) {
1918 my $pid = open my $pipe, '-|';
1919 defined $pid or croak $!;
1920 if ($pid == 0) {
098749d9 1921 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
b8c92cad 1922 or croak $!;
69f0d91e
EW
1923 }
1924 while (<$pipe>) {
1925 if (/^commit ($sha1)$/o) {
1926 my $commit = $1;
098749d9
EW
1927
1928 # if we've seen a commit,
1929 # we've seen its parents
1930 last if $seen{$commit};
69f0d91e
EW
1931 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1932 unless (defined $tree) {
1933 die "Failed to parse commit $commit\n";
1934 }
1935 push @{$tree_map{$tree}}, $commit;
098749d9 1936 $seen{$commit} = 1;
69f0d91e
EW
1937 }
1938 }
098749d9 1939 close $pipe; # we could be breaking the pipe early
69f0d91e
EW
1940 }
1941}
1942
bf78b1d8
EW
1943sub load_all_refs {
1944 if (@_branch_from) {
1945 print STDERR '--branch|-b parameters are ignored when ',
1946 "--branch-all-refs|-B is passed\n";
1947 }
1948
1949 # don't worry about rev-list on non-commit objects/tags,
1950 # it shouldn't blow up if a ref is a blob or tree...
1951 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1952}
1953
eeb0abe0
EW
1954# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1955sub load_authors {
1956 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1957 while (<$authors>) {
1958 chomp;
1959 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1960 my ($user, $name, $email) = ($1, $2, $3);
1961 $users{$user} = [$name, $email];
1962 }
1963 close $authors or croak $!;
1964}
1965
79bb8d88
EW
1966sub rload_authors {
1967 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1968 while (<$authors>) {
1969 chomp;
1970 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1971 my ($user, $name, $email) = ($1, $2, $3);
1972 $rusers{"$name <$email>"} = $user;
1973 }
1974 close $authors or croak $!;
1975}
1976
8a97e368
EW
1977sub svn_propget_base {
1978 my ($p, $f) = @_;
1979 $f .= '@BASE' if $_svn_pg_peg_revs;
1980 return safe_qx(qw/svn propget/, $p, $f);
1981}
1982
9d55b41a
EW
1983sub git_svn_each {
1984 my $sub = shift;
1985 foreach (`git-rev-parse --symbolic --all`) {
1986 next unless s#^refs/remotes/##;
1987 chomp $_;
1988 next unless -f "$GIT_DIR/svn/$_/info/url";
1989 &$sub($_);
1990 }
1991}
1992
883d0a78
EW
1993sub migration_check {
1994 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1995 print "Upgrading repository...\n";
1996 unless (-d "$GIT_DIR/svn") {
1997 mkdir "$GIT_DIR/svn" or croak $!;
1998 }
1999 print "Data from a previous version of git-svn exists, but\n\t",
2000 "$GIT_SVN_DIR\n\t(required for this version ",
2001 "($VERSION) of git-svn) does not.\n";
2002
2003 foreach my $x (`git-rev-parse --symbolic --all`) {
2004 next unless $x =~ s#^refs/remotes/##;
2005 chomp $x;
2006 next unless -f "$GIT_DIR/$x/info/url";
2007 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2008 next unless $u;
2009 my $dn = dirname("$GIT_DIR/svn/$x");
2010 mkpath([$dn]) unless -d $dn;
2011 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2012 my ($url, $path) = repo_path_split($u);
2013 s_to_file($url, "$GIT_DIR/svn/$x/info/repo_url");
2014 s_to_file($path, "$GIT_DIR/svn/$x/info/repo_path");
2015 }
2016 print "Done upgrading.\n";
2017}
2018
9d55b41a
EW
2019sub find_rev_before {
2020 my ($r, $git_svn_id) = @_;
2021 my @revs = map { basename $_ } <$GIT_DIR/svn/$git_svn_id/revs/*>;
2022 foreach my $r0 (sort { $b <=> $a } @revs) {
2023 next if $r0 >= $r;
2024 return ($r0, file_to_s("$GIT_DIR/svn/$git_svn_id/revs/$r0"));
2025 }
2026 return (undef, undef);
2027}
2028
b8c92cad
EW
2029sub init_vars {
2030 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2031 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2032 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2033 $SVN_URL = undef;
2034 $REV_DIR = "$GIT_SVN_DIR/revs";
2035 $SVN_WC = "$GIT_SVN_DIR/tree";
2036}
2037
2038# convert GetOpt::Long specs for use by git-repo-config
2039sub read_repo_config {
2040 return unless -d $GIT_DIR;
2041 my $opts = shift;
2042 foreach my $o (keys %$opts) {
2043 my $v = $opts->{$o};
2044 my ($key) = ($o =~ /^([a-z\-]+)/);
2045 $key =~ s/-//g;
2046 my $arg = 'git-repo-config';
2047 $arg .= ' --int' if ($o =~ /[:=]i$/);
2048 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2049 if (ref $v eq 'ARRAY') {
2050 chomp(my @tmp = `$arg --get-all svn.$key`);
2051 @$v = @tmp if @tmp;
2052 } else {
2053 chomp(my $tmp = `$arg --get svn.$key`);
2054 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2055 $$v = $tmp;
2056 }
2057 }
2058 }
2059}
2060
dc5869c0
EW
2061sub set_default_vals {
2062 if (defined $_repack) {
2063 $_repack = 1000 if ($_repack <= 0);
2064 $_repack_nr = $_repack;
2065 $_repack_flags ||= '';
2066 }
2067}
2068
9d55b41a
EW
2069sub read_grafts {
2070 my $gr_file = shift;
2071 my ($grafts, $comments) = ({}, {});
2072 if (open my $fh, '<', $gr_file) {
2073 my @tmp;
2074 while (<$fh>) {
2075 if (/^($sha1)\s+/) {
2076 my $c = $1;
2077 if (@tmp) {
2078 @{$comments->{$c}} = @tmp;
2079 @tmp = ();
2080 }
2081 foreach my $p (split /\s+/, $_) {
2082 $grafts->{$c}->{$p} = 1;
2083 }
2084 } else {
2085 push @tmp, $_;
2086 }
2087 }
2088 close $fh or croak $!;
2089 @{$comments->{'END'}} = @tmp if @tmp;
2090 }
2091 return ($grafts, $comments);
2092}
2093
2094sub write_grafts {
2095 my ($grafts, $comments, $gr_file) = @_;
2096
2097 open my $fh, '>', $gr_file or croak $!;
2098 foreach my $c (sort keys %$grafts) {
2099 if ($comments->{$c}) {
2100 print $fh $_ foreach @{$comments->{$c}};
2101 }
2102 my $p = $grafts->{$c};
2103 delete $p->{$c}; # commits are not self-reproducing...
2104 my $pid = open my $ch, '-|';
2105 defined $pid or croak $!;
2106 if (!$pid) {
2107 exec(qw/git-cat-file commit/, $c) or croak $!;
2108 }
2109 while (<$ch>) {
2110 if (/^parent ([a-f\d]{40})/) {
2111 $p->{$1} = 1;
2112 } else {
2113 last unless /^\S/i;
2114 }
2115 }
2116 close $ch; # breaking the pipe
2117 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2118 }
2119 if ($comments->{'END'}) {
2120 print $fh $_ foreach @{$comments->{'END'}};
2121 }
2122 close $fh or croak $!;
2123}
2124
2125sub read_url_paths {
2126 my $l_map = {};
2127 git_svn_each(sub { my $x = shift;
2128 my $u = file_to_s("$GIT_DIR/svn/$x/info/repo_url");
2129 my $p = file_to_s("$GIT_DIR/svn/$x/info/repo_path");
2130 # we hate trailing slashes
2131 if ($u =~ s#(?:^\/+|\/+$)##g) {
2132 s_to_file($u,"$GIT_DIR/svn/$x/info/repo_url");
2133 }
2134 if ($p =~ s#(?:^\/+|\/+$)##g) {
2135 s_to_file($p,"$GIT_DIR/svn/$x/info/repo_path");
2136 }
2137 $l_map->{$u}->{$p} = $x;
2138 });
2139 return $l_map;
2140}
2141
79bb8d88
EW
2142sub extract_metadata {
2143 my $id = shift;
2144 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2145 \s([a-f\d\-]+)$/x);
2146 if (!$rev || !$uuid || !$url) {
2147 # some of the original repositories I made had
2148 # indentifiers like this:
2149 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2150 }
2151 return ($url, $rev, $uuid);
2152}
2153
2154sub tz_to_s_offset {
2155 my ($tz) = @_;
2156 $tz =~ s/(\d\d)$//;
2157 return ($1 * 60) + ($tz * 3600);
2158}
2159
2160sub setup_pager { # translated to Perl from pager.c
2161 return unless (-t *STDOUT);
2162 my $pager = $ENV{PAGER};
2163 if (!defined $pager) {
2164 $pager = 'less';
2165 } elsif (length $pager == 0 || $pager eq 'cat') {
2166 return;
2167 }
2168 pipe my $rfd, my $wfd or return;
2169 defined(my $pid = fork) or croak $!;
2170 if (!$pid) {
2171 open STDOUT, '>&', $wfd or croak $!;
2172 return;
2173 }
2174 open STDIN, '<&', $rfd or croak $!;
2175 $ENV{LESS} ||= '-S';
2176 exec $pager or croak "Can't run pager: $!\n";;
2177}
2178
2179sub get_author_info {
2180 my ($dest, $author, $t, $tz) = @_;
2181 $author =~ s/(?:^\s*|\s*$)//g;
2182 my $_a;
2183 if ($_authors) {
2184 $_a = $rusers{$author} || undef;
2185 }
2186 if (!$_a) {
2187 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2188 }
2189 $dest->{t} = $t;
2190 $dest->{tz} = $tz;
2191 $dest->{a} = $_a;
2192 # Date::Parse isn't in the standard Perl distro :(
2193 if ($tz =~ s/^\+//) {
2194 $t += tz_to_s_offset($tz);
2195 } elsif ($tz =~ s/^\-//) {
2196 $t -= tz_to_s_offset($tz);
2197 }
2198 $dest->{t_utc} = $t;
2199}
2200
2201sub process_commit {
2202 my ($c, $r_min, $r_max, $defer) = @_;
2203 if (defined $r_min && defined $r_max) {
2204 if ($r_min == $c->{r} && $r_min == $r_max) {
2205 show_commit($c);
2206 return 0;
2207 }
2208 return 1 if $r_min == $r_max;
2209 if ($r_min < $r_max) {
2210 # we need to reverse the print order
2211 return 0 if (defined $_limit && --$_limit < 0);
2212 push @$defer, $c;
2213 return 1;
2214 }
2215 if ($r_min != $r_max) {
2216 return 1 if ($r_min < $c->{r});
2217 return 1 if ($r_max > $c->{r});
2218 }
2219 }
2220 return 0 if (defined $_limit && --$_limit < 0);
2221 show_commit($c);
2222 return 1;
2223}
2224
2225sub show_commit {
2226 my $c = shift;
2227 if ($_oneline) {
2228 my $x = "\n";
2229 if (my $l = $c->{l}) {
2230 while ($l->[0] =~ /^\s*$/) { shift @$l }
2231 $x = $l->[0];
2232 }
2233 $_l_fmt ||= 'A' . length($c->{r});
2234 print 'r',pack($_l_fmt, $c->{r}),' | ';
2235 print "$c->{c} | " if $_show_commit;
2236 print $x;
2237 } else {
2238 show_commit_normal($c);
2239 }
2240}
2241
2242sub show_commit_normal {
2243 my ($c) = @_;
2244 print '-' x72, "\nr$c->{r} | ";
2245 print "$c->{c} | " if $_show_commit;
2246 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2247 localtime($c->{t_utc})), ' | ';
2248 my $nr_line = 0;
2249
2250 if (my $l = $c->{l}) {
2251 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2252 pop @$l;
2253 }
2254 $nr_line = scalar @$l;
2255 if (!$nr_line) {
2256 print "1 line\n\n\n";
2257 } else {
2258 if ($nr_line == 1) {
2259 $nr_line = '1 line';
2260 } else {
2261 $nr_line .= ' lines';
2262 }
2263 print $nr_line, "\n\n";
2264 print $_ foreach @$l;
2265 }
2266 } else {
2267 print "1 line\n\n";
2268
2269 }
2270 foreach my $x (qw/raw diff/) {
2271 if ($c->{$x}) {
2272 print "\n";
2273 print $_ foreach @{$c->{$x}}
2274 }
2275 }
2276}
2277
a5e0cedc
EW
2278sub libsvn_load {
2279 return unless $_use_lib;
2280 $_use_lib = eval {
2281 require SVN::Core;
2282 if ($SVN::Core::VERSION lt '1.2.1') {
2283 die "Need SVN::Core 1.2.1 or better ",
2284 "(got $SVN::Core::VERSION) ",
2285 "Falling back to command-line svn\n";
2286 }
2287 require SVN::Ra;
2288 require SVN::Delta;
2289 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2290 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2291 $SVN::Node::dir.$SVN::Node::unknown.
2292 $SVN::Node::none.$SVN::Node::file.
2293 $SVN::Node::dir.$SVN::Node::unknown;
2294 1;
2295 };
2296}
2297
2298sub libsvn_connect {
2299 my ($url) = @_;
2300 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2301 SVN::Client::get_ssl_server_trust_file_provider(),
2302 SVN::Client::get_username_provider()]);
2303 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2304 return $s;
2305}
2306
2307sub libsvn_get_file {
2308 my ($gui, $f, $rev) = @_;
2309 my $p = $f;
2310 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2311
2312 my $fd = IO::File->new_tmpfile or croak $!;
2313 my $pool = SVN::Pool->new;
2314 my ($r, $props) = $SVN->get_file($f, $rev, $fd, $pool);
2315 $pool->clear;
2316 $fd->flush == 0 or croak $!;
2317 seek $fd, 0, 0 or croak $!;
2318 if (my $es = $props->{'svn:eol-style'}) {
2319 my $new_fd = IO::File->new_tmpfile or croak $!;
2320 eol_cp_fd($fd, $new_fd, $es);
2321 close $fd or croak $!;
2322 $fd = $new_fd;
2323 seek $fd, 0, 0 or croak $!;
2324 $fd->flush == 0 or croak $!;
2325 }
2326 my $mode = '100644';
2327 if (exists $props->{'svn:executable'}) {
2328 $mode = '100755';
2329 }
2330 if (exists $props->{'svn:special'}) {
2331 $mode = '120000';
2332 local $/;
2333 my $link = <$fd>;
2334 $link =~ s/^link // or die "svn:special file with contents: <",
2335 $link, "> is not understood\n";
2336 seek $fd, 0, 0 or croak $!;
2337 truncate $fd, 0 or croak $!;
2338 print $fd $link or croak $!;
2339 seek $fd, 0, 0 or croak $!;
2340 $fd->flush == 0 or croak $!;
2341 }
2342 my $pid = open my $ho, '-|';
2343 defined $pid or croak $!;
2344 if (!$pid) {
2345 open STDIN, '<&', $fd or croak $!;
2346 exec qw/git-hash-object -w --stdin/ or croak $!;
2347 }
2348 chomp(my $hash = do { local $/; <$ho> });
2349 close $ho or croak $?;
2350 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2351 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2352 close $fd or croak $!;
2353}
2354
2355sub libsvn_log_entry {
2356 my ($rev, $author, $date, $msg, $parents) = @_;
2357 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2358 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2359 or die "Unable to parse date: $date\n";
2360 if (defined $_authors && ! defined $users{$author}) {
2361 die "Author: $author not defined in $_authors file\n";
2362 }
2363 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2364 author => $author, msg => $msg."\n", parents => $parents || [] }
2365}
2366
2367sub process_rm {
2368 my ($gui, $last_commit, $f) = @_;
2369 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2370 # remove entire directories.
2371 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2372 defined(my $pid = open my $ls, '-|') or croak $!;
2373 if (!$pid) {
2374 exec(qw/git-ls-tree -r --name-only -z/,
2375 $last_commit,'--',$f) or croak $!;
2376 }
2377 local $/ = "\0";
2378 while (<$ls>) {
2379 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2380 }
2381 close $ls or croak $!;
2382 } else {
2383 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2384 }
2385}
2386
2387sub libsvn_fetch {
2388 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2389 open my $gui, '| git-update-index -z --index-info' or croak $!;
2390 my @amr;
2391 foreach my $f (keys %$paths) {
2392 my $m = $paths->{$f}->action();
2393 $f =~ s#^/+##;
2394 if ($m =~ /^[DR]$/) {
2395 process_rm($gui, $last_commit, $f);
2396 next if $m eq 'D';
2397 # 'R' can be file replacements, too, right?
2398 }
2399 my $pool = SVN::Pool->new;
2400 my $t = $SVN->check_path($f, $rev, $pool);
2401 if ($t == $SVN::Node::file) {
2402 if ($m =~ /^[AMR]$/) {
2403 push @amr, $f;
2404 } else {
2405 die "Unrecognized action: $m, ($f r$rev)\n";
2406 }
2407 }
2408 $pool->clear;
2409 }
2410 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2411 close $gui or croak $!;
2412 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2413}
2414
2415sub svn_grab_base_rev {
2416 defined(my $pid = open my $fh, '-|') or croak $!;
2417 if (!$pid) {
2418 open my $null, '>', '/dev/null' or croak $!;
2419 open STDERR, '>&', $null or croak $!;
2420 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2421 or croak $!;
2422 }
2423 chomp(my $c = do { local $/; <$fh> });
2424 close $fh;
2425 if (defined $c && length $c) {
2426 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2427 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2428 return ($rev, $c);
2429 }
2430 return (undef, undef);
2431}
2432
2433sub libsvn_parse_revision {
2434 my $base = shift;
2435 my $head = $SVN->get_latest_revnum();
2436 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2437 return ($base + 1, $head) if (defined $base);
2438 return (0, $head);
2439 }
2440 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2441 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2442 if ($_revision =~ /^BASE:(\d+)$/) {
2443 return ($base + 1, $1) if (defined $base);
2444 return (0, $head);
2445 }
2446 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2447 die "revision argument: $_revision not understood by git-svn\n",
2448 "Try using the command-line svn client instead\n";
2449}
2450
2451sub libsvn_traverse {
2452 my ($gui, $pfx, $path, $rev) = @_;
2453 my $cwd = "$pfx/$path";
2454 my $pool = SVN::Pool->new;
2455 $cwd =~ s#^/+##g;
2456 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2457 foreach my $d (keys %$dirent) {
2458 my $t = $dirent->{$d}->kind;
2459 if ($t == $SVN::Node::dir) {
2460 libsvn_traverse($gui, $cwd, $d, $rev);
2461 } elsif ($t == $SVN::Node::file) {
2462 libsvn_get_file($gui, "$cwd/$d", $rev);
2463 }
2464 }
2465 $pool->clear;
2466}
2467
2468sub libsvn_traverse_ignore {
2469 my ($fh, $path, $r) = @_;
2470 $path =~ s#^/+##g;
2471 my $pool = SVN::Pool->new;
2472 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2473 my $p = $path;
2474 $p =~ s#^\Q$SVN_PATH\E/?##;
2475 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2476 if (my $s = $props->{'svn:ignore'}) {
2477 $s =~ s/[\r\n]+/\n/g;
2478 chomp $s;
2479 if (length $p == 0) {
2480 $s =~ s#\n#\n/$p#g;
2481 print $fh "/$s\n";
2482 } else {
2483 $s =~ s#\n#\n/$p/#g;
2484 print $fh "/$p/$s\n";
2485 }
2486 }
2487 foreach (sort keys %$dirent) {
2488 next if $dirent->{$_}->kind != $SVN::Node::dir;
2489 libsvn_traverse_ignore($fh, "$path/$_", $r);
2490 }
2491 $pool->clear;
2492}
2493
2494sub libsvn_new_tree {
2495 my ($paths, $rev, $author, $date, $msg) = @_;
2496 my $svn_path = '/'.$SVN_PATH;
2497
2498 # look for a parent from another branch:
2499 foreach (keys %$paths) {
2500 next if ($_ ne $svn_path);
2501 my $i = $paths->{$_};
2502 my $branch_from = $i->copyfrom_path or next;
2503 my $r = $i->copyfrom_rev;
2504 print STDERR "Found possible branch point: ",
2505 "$branch_from => $svn_path, $r\n";
2506 $branch_from =~ s#^/##;
2507 my $l_map = read_url_paths();
2508 my $url = $SVN->{url};
2509 defined $l_map->{$url} or next;
2510 my $id = $l_map->{$url}->{$branch_from} or next;
2511 my $f = "$GIT_DIR/svn/$id/revs/$r";
2512 while ($r && !-r $f) {
2513 $r--;
2514 $f = "$GIT_DIR/svn/$id/revs/$r";
2515 }
2516 if (-r $f) {
2517 my $parent = file_to_s($f);
2518 unlink $GIT_SVN_INDEX;
2519 print STDERR "Found branch parent: $parent\n";
2520 sys(qw/git-read-tree/, $parent);
2521 return libsvn_fetch($parent, $paths, $rev,
2522 $author, $date, $msg);
2523 }
2524 print STDERR "Nope, branch point not imported or unknown\n";
2525 }
2526 open my $gui, '| git-update-index -z --index-info' or croak $!;
2527 my $pool = SVN::Pool->new;
2528 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2529 $pool->clear;
2530 close $gui or croak $!;
2531 return libsvn_log_entry($rev, $author, $date, $msg);
2532}
2533
2534sub find_graft_path_commit {
2535 my ($tree_paths, $p1, $r1) = @_;
2536 foreach my $x (keys %$tree_paths) {
2537 next unless ($p1 =~ /^\Q$x\E/);
2538 my $i = $tree_paths->{$x};
2539 my $f = "$GIT_DIR/svn/$i/revs/$r1";
2540
2541 return file_to_s($f) if (-r $f);
2542
2543 print STDERR "r$r1 of $i not imported\n";
2544 next;
2545 }
2546 return undef;
2547}
2548
2549sub find_graft_path_parents {
2550 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2551 foreach my $x (keys %$tree_paths) {
2552 next unless ($p0 =~ /^\Q$x\E/);
2553 my $i = $tree_paths->{$x};
2554 my $f = "$GIT_DIR/svn/$i/revs/$r0";
2555 while ($r0 && !-r $f) {
2556 # could be an older revision, too...
2557 $r0--;
2558 $f = "$GIT_DIR/svn/$i/revs/$r0";
2559 }
2560 unless (-r $f) {
2561 print STDERR "r$r0 of $i not imported\n";
2562 next;
2563 }
2564 my $parent = file_to_s($f);
2565 $grafts->{$c}->{$parent} = 1;
2566 }
2567}
2568
2569sub libsvn_graft_file_copies {
2570 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2571 foreach (keys %$paths) {
2572 my $i = $paths->{$_};
2573 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2574 $i->copyfrom_rev);
2575 next unless (defined $p0 && defined $r0);
2576
2577 my $p1 = $_;
2578 $p1 =~ s#^/##;
2579 $p0 =~ s#^/##;
2580 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2581 next unless $c;
2582 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2583 }
2584}
2585
2586sub set_index {
2587 my $old = $ENV{GIT_INDEX_FILE};
2588 $ENV{GIT_INDEX_FILE} = shift;
2589 return $old;
2590}
2591
2592sub restore_index {
2593 my ($old) = @_;
2594 if (defined $old) {
2595 $ENV{GIT_INDEX_FILE} = $old;
2596 } else {
2597 delete $ENV{GIT_INDEX_FILE};
2598 }
2599}
2600
2601sub libsvn_commit_cb {
2602 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2603 if ($rev == ($r_last + 1)) {
2604 # optimized (avoid fetch)
2605 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2606 $log->{tree} = get_tree_from_treeish($c);
2607 my $cmt = git_commit($log, $cmt_last, $c);
2608 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2609 if (@diff) {
2610 print STDERR "Trees differ: $cmt $c\n",
2611 join('',@diff),"\n";
2612 exit 1;
2613 }
2614 } else {
2615 fetch_lib("$rev=$c");
2616 }
2617}
2618
2619sub libsvn_ls_fullurl {
2620 my $fullurl = shift;
2621 my ($repo, $path) = repo_path_split($fullurl);
2622 $SVN ||= libsvn_connect($repo);
2623 my @ret;
2624 my $pool = SVN::Pool->new;
2625 my ($dirent, undef, undef) = $SVN->get_dir($path,
2626 $SVN->get_latest_revnum, $pool);
2627 foreach my $d (keys %$dirent) {
2628 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2629 push @ret, "$d/"; # add '/' for compat with cli svn
2630 }
2631 }
2632 $pool->clear;
2633 return @ret;
2634}
2635
2636
2637sub libsvn_skip_unknown_revs {
2638 my $err = shift;
2639 my $errno = $err->apr_err();
2640 # Maybe the branch we're tracking didn't
2641 # exist when the repo started, so it's
2642 # not an error if it doesn't, just continue
2643 #
2644 # Wonderfully consistent library, eh?
2645 # 160013 - svn:// and file://
2646 # 175002 - http(s)://
2647 # More codes may be discovered later...
2648 if ($errno == 175002 || $errno == 160013) {
2649 print STDERR "directory non-existent\n";
2650 return;
2651 }
2652 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2653};
2654
2655package SVN::Git::Editor;
2656use vars qw/@ISA/;
2657use strict;
2658use warnings;
2659use Carp qw/croak/;
2660use IO::File;
2661
2662sub new {
2663 my $class = shift;
2664 my $git_svn = shift;
2665 my $self = SVN::Delta::Editor->new(@_);
2666 bless $self, $class;
2667 foreach (qw/svn_path c r ra /) {
2668 die "$_ required!\n" unless (defined $git_svn->{$_});
2669 $self->{$_} = $git_svn->{$_};
2670 }
2671 $self->{pool} = SVN::Pool->new;
2672 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2673 $self->{rm} = { };
2674 require Digest::MD5;
2675 return $self;
2676}
2677
2678sub split_path {
2679 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2680}
2681
2682sub repo_path {
2683 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2684 : $_[0]->{svn_path}
2685}
2686
2687sub url_path {
2688 my ($self, $path) = @_;
2689 $self->{ra}->{url} . '/' . $self->repo_path($path);
2690}
2691
2692sub rmdirs {
2693 my ($self) = @_;
2694 my $rm = $self->{rm};
2695 delete $rm->{''}; # we never delete the url we're tracking
2696 return unless %$rm;
2697
2698 foreach (keys %$rm) {
2699 my @d = split m#/#, $_;
2700 my $c = shift @d;
2701 $rm->{$c} = 1;
2702 while (@d) {
2703 $c .= '/' . shift @d;
2704 $rm->{$c} = 1;
2705 }
2706 }
2707 delete $rm->{$self->{svn_path}};
2708 delete $rm->{''}; # we never delete the url we're tracking
2709 return unless %$rm;
2710
2711 defined(my $pid = open my $fh,'-|') or croak $!;
2712 if (!$pid) {
2713 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2714 }
2715 local $/ = "\0";
2716 while (<$fh>) {
2717 chomp;
2718 $_ = $self->{svn_path} . '/' . $_;
2719 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2720 delete $rm->{$dn};
2721 last unless %$rm;
2722 }
2723 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2724 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2725 $self->close_directory($bat->{$d}, $p);
2726 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2727 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2728 delete $bat->{$d};
2729 }
2730}
2731
2732sub open_or_add_dir {
2733 my ($self, $full_path, $baton) = @_;
2734 my $p = SVN::Pool->new;
2735 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2736 $p->clear;
2737 if ($t == $SVN::Node::none) {
2738 return $self->add_directory($full_path, $baton,
2739 undef, -1, $self->{pool});
2740 } elsif ($t == $SVN::Node::dir) {
2741 return $self->open_directory($full_path, $baton,
2742 $self->{r}, $self->{pool});
2743 }
2744 print STDERR "$full_path already exists in repository at ",
2745 "r$self->{r} and it is not a directory (",
2746 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2747 exit 1;
2748}
2749
2750sub ensure_path {
2751 my ($self, $path) = @_;
2752 my $bat = $self->{bat};
2753 $path = $self->repo_path($path);
2754 return $bat->{''} unless (length $path);
2755 my @p = split m#/+#, $path;
2756 my $c = shift @p;
2757 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2758 while (@p) {
2759 my $c0 = $c;
2760 $c .= '/' . shift @p;
2761 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2762 }
2763 return $bat->{$c};
2764}
2765
2766sub A {
2767 my ($self, $m) = @_;
2768 my ($dir, $file) = split_path($m->{file_b});
2769 my $pbat = $self->ensure_path($dir);
2770 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2771 undef, -1);
2772 $self->chg_file($fbat, $m);
2773 $self->close_file($fbat,undef,$self->{pool});
2774}
2775
2776sub C {
2777 my ($self, $m) = @_;
2778 my ($dir, $file) = split_path($m->{file_b});
2779 my $pbat = $self->ensure_path($dir);
2780 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2781 $self->url_path($m->{file_a}), $self->{r});
2782 $self->chg_file($fbat, $m);
2783 $self->close_file($fbat,undef,$self->{pool});
2784}
2785
2786sub delete_entry {
2787 my ($self, $path, $pbat) = @_;
2788 my $rpath = $self->repo_path($path);
2789 my ($dir, $file) = split_path($rpath);
2790 $self->{rm}->{$dir} = 1;
2791 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2792}
2793
2794sub R {
2795 my ($self, $m) = @_;
2796 my ($dir, $file) = split_path($m->{file_b});
2797 my $pbat = $self->ensure_path($dir);
2798 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2799 $self->url_path($m->{file_a}), $self->{r});
2800 $self->chg_file($fbat, $m);
2801 $self->close_file($fbat,undef,$self->{pool});
2802
2803 ($dir, $file) = split_path($m->{file_a});
2804 $pbat = $self->ensure_path($dir);
2805 $self->delete_entry($m->{file_a}, $pbat);
2806}
2807
2808sub M {
2809 my ($self, $m) = @_;
2810 my ($dir, $file) = split_path($m->{file_b});
2811 my $pbat = $self->ensure_path($dir);
2812 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2813 $pbat,$self->{r},$self->{pool});
2814 $self->chg_file($fbat, $m);
2815 $self->close_file($fbat,undef,$self->{pool});
2816}
2817
2818sub T { shift->M(@_) }
2819
2820sub change_file_prop {
2821 my ($self, $fbat, $pname, $pval) = @_;
2822 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2823}
2824
2825sub chg_file {
2826 my ($self, $fbat, $m) = @_;
2827 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2828 $self->change_file_prop($fbat,'svn:executable','*');
2829 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2830 $self->change_file_prop($fbat,'svn:executable',undef);
2831 }
2832 my $fh = IO::File->new_tmpfile or croak $!;
2833 if ($m->{mode_b} =~ /^120/) {
2834 print $fh 'link ' or croak $!;
2835 $self->change_file_prop($fbat,'svn:special','*');
2836 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2837 $self->change_file_prop($fbat,'svn:special',undef);
2838 }
2839 defined(my $pid = fork) or croak $!;
2840 if (!$pid) {
2841 open STDOUT, '>&', $fh or croak $!;
2842 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2843 }
2844 waitpid $pid, 0;
2845 croak $? if $?;
2846 $fh->flush == 0 or croak $!;
2847 seek $fh, 0, 0 or croak $!;
2848
2849 my $md5 = Digest::MD5->new;
2850 $md5->addfile($fh) or croak $!;
2851 seek $fh, 0, 0 or croak $!;
2852
2853 my $exp = $md5->hexdigest;
2854 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2855 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2856 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2857
2858 close $fh or croak $!;
2859}
2860
2861sub D {
2862 my ($self, $m) = @_;
2863 my ($dir, $file) = split_path($m->{file_b});
2864 my $pbat = $self->ensure_path($dir);
2865 $self->delete_entry($m->{file_b}, $pbat);
2866}
2867
2868sub close_edit {
2869 my ($self) = @_;
2870 my ($p,$bat) = ($self->{pool}, $self->{bat});
2871 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2872 $self->close_directory($bat->{$_}, $p);
2873 }
2874 $self->SUPER::close_edit($p);
2875 $p->clear;
2876}
2877
2878sub abort_edit {
2879 my ($self) = @_;
2880 $self->SUPER::abort_edit($self->{pool});
2881 $self->{pool}->clear;
2882}
2883
3397f9df
EW
2884__END__
2885
2886Data structures:
2887
03823184
EW
2888$svn_log hashref (as returned by svn_log_raw)
2889{
2890 fh => file handle of the log file,
2891 state => state of the log file parser (sep/msg/rev/msg_start...)
2892}
3397f9df 2893
03823184 2894$log_msg hashref as returned by next_log_entry($svn_log)
3397f9df
EW
2895{
2896 msg => 'whitespace-formatted log entry
2897', # trailing newline is preserved
2898 revision => '8', # integer
2899 date => '2004-02-24T17:01:44.108345Z', # commit date
2900 author => 'committer name'
2901};
2902
2903
2904@mods = array of diff-index line hashes, each element represents one line
2905 of diff-index output
2906
2907diff-index line ($m hash)
2908{
2909 mode_a => first column of diff-index output, no leading ':',
2910 mode_b => second column of diff-index output,
2911 sha1_b => sha1sum of the final blob,
ac8e0b91 2912 chg => change type [MCRADT],
3397f9df
EW
2913 file_a => original file name of a file (iff chg is 'C' or 'R')
2914 file_b => new/current file name of a file (any chg)
2915}
2916;
a5e0cedc
EW
2917
2918Notes:
2919 I don't trust the each() function on unless I created %hash myself
2920 because the internal iterator may not have started at base.