sha1_object_info(): be consistent with read_sha1_file()
[git/git.git] / 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
42d32870 9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
3397f9df 10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 11$VERSION = '@@GIT_VERSION@@';
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';
a00439ac 22$| = 1; # unbuffer STDOUT
3397f9df 23
d25c26e7 24sub fatal (@) { print STDERR $@; exit 1 }
3397f9df
EW
25# If SVN:: library support is added, please make the dependencies
26# optional and preserve the capability to use the command-line client.
ce6f3519 27# use eval { require SVN::... } to make it lazy load
eeb0abe0 28# We don't use any modules not in the standard Perl distribution:
3397f9df
EW
29use Carp qw/croak/;
30use IO::File qw//;
31use File::Basename qw/dirname basename/;
32use File::Path qw/mkpath/;
79bb8d88 33use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
3397f9df 34use File::Spec qw//;
17a10f37 35use File::Copy qw/copy/;
e17512f3 36use POSIX qw/strftime/;
968bdf1f 37use IPC::Open3;
42d32870
EW
38use Memoize;
39memoize('revisions_eq');
c1927a85
EW
40memoize('cmt_metadata');
41memoize('get_commit_time');
a5e0cedc 42
747fa12c 43my ($SVN, $_use_lib);
83e9940a
EW
44
45sub nag_lib {
46 print STDERR <<EOF;
47! Please consider installing the SVN Perl libraries (version 1.1.0 or
48! newer). You will generally get better performance and fewer bugs,
49! especially if you:
50! 1) have a case-insensitive filesystem
51! 2) replace symlinks with files (and vice-versa) in commits
52
53EOF
54}
55
a5e0cedc
EW
56$_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
57libsvn_load();
83e9940a
EW
58nag_lib() unless $_use_lib;
59
42d32870 60my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
3397f9df 61my $sha1 = qr/[a-f\d]{40}/;
ac8e0b91 62my $sha1_short = qr/[a-f\d]{4,40}/;
72942938 63my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
1a82e793 64 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
80f50749 65 $_repack, $_repack_nr, $_repack_flags, $_q,
a00439ac 66 $_message, $_file, $_follow_parent, $_no_metadata,
9d55b41a 67 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
79bb8d88 68 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
b22d4497 69 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
30d055aa
EW
70 $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
71 $_username, $_config_dir, $_no_auth_cache);
42d32870 72my (@_branch_from, %tree_map, %users, %rusers, %equiv);
8a97e368 73my ($_svn_co_url_revs, $_svn_pg_peg_revs);
883d0a78 74my @repo_path_split_cache;
3397f9df 75
eeb0abe0 76my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
69f0d91e 77 'branch|b=s' => \@_branch_from,
a00439ac 78 'follow-parent|follow' => \$_follow_parent,
bf78b1d8 79 'branch-all-refs|B' => \$_branch_all_refs,
dc5869c0
EW
80 'authors-file|A=s' => \$_authors,
81 'repack:i' => \$_repack,
a00439ac 82 'no-metadata' => \$_no_metadata,
80f50749 83 'quiet|q' => \$_q,
30d055aa
EW
84 'username=s' => \$_username,
85 'config-dir=s' => \$_config_dir,
86 'no-auth-cache' => \$_no_auth_cache,
f7bae37f 87 'ignore-nodate' => \$_ignore_nodate,
dc5869c0 88 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
36f5b1f0 89
9d55b41a
EW
90my ($_trunk, $_tags, $_branches);
91my %multi_opts = ( 'trunk|T=s' => \$_trunk,
92 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches );
94my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
27e9fb8d
EW
95my %cmt_opts = ( 'edit|e' => \$_edit,
96 'rmdir' => \$_rmdir,
97 'find-copies-harder' => \$_find_copies_harder,
98 'l=i' => \$_l,
99 'copy-similarity|C=i'=> \$_cp_similarity
100);
9d55b41a 101
3397f9df 102my %cmd = (
eeb0abe0
EW
103 fetch => [ \&fetch, "Download new revisions from SVN",
104 { 'revision|r=s' => \$_revision, %fc_opts } ],
81c5a0e6 105 init => [ \&init, "Initialize a repo for tracking" .
f8ab6b73 106 " (requires URL argument)",
9d55b41a 107 \%init_opts ],
eeb0abe0 108 commit => [ \&commit, "Commit git revisions to SVN",
27e9fb8d 109 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
a5e0cedc
EW
110 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
111 { 'revision|r=i' => \$_revision } ],
eeb0abe0
EW
112 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
113 { 'no-ignore-externals' => \$_no_ignore_ext,
1a82e793 114 'copy-remote|remote=s' => \$_cp_remote,
eeb0abe0 115 'upgrade' => \$_upgrade } ],
9d55b41a
EW
116 'graft-branches' => [ \&graft_branches,
117 'Detect merges/branches from already imported history',
118 { 'merge-rx|m' => \@_opt_m,
c1927a85
EW
119 'branch|b=s' => \@_branch_from,
120 'branch-all-refs|B' => \$_branch_all_refs,
9d55b41a
EW
121 'no-default-regex' => \$_no_default_regex,
122 'no-graft-copy' => \$_no_graft_copy } ],
123 'multi-init' => [ \&multi_init,
124 'Initialize multiple trees (like git-svnimport)',
125 { %multi_opts, %fc_opts } ],
126 'multi-fetch' => [ \&multi_fetch,
127 'Fetch multiple trees (like git-svnimport)',
128 \%fc_opts ],
79bb8d88
EW
129 'log' => [ \&show_log, 'Show commit logs',
130 { 'limit=i' => \$_limit,
131 'revision|r=s' => \$_revision,
132 'verbose|v' => \$_verbose,
133 'incremental' => \$_incremental,
134 'oneline' => \$_oneline,
135 'show-commit' => \$_show_commit,
74a31a10 136 'non-recursive' => \$_non_recursive,
79bb8d88
EW
137 'authors-file|A=s' => \$_authors,
138 } ],
27e9fb8d
EW
139 'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
140 { 'message|m=s' => \$_message,
141 'file|F=s' => \$_file,
45bf473a 142 'revision|r=s' => \$_revision,
27e9fb8d 143 %cmt_opts } ],
b22d4497
EW
144 dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
145 { 'merge|m|M' => \$_merge,
146 'strategy|s=s' => \$_strategy,
147 'dry-run|n' => \$_dry_run,
148 %cmt_opts } ],
3397f9df 149);
9d55b41a 150
3397f9df
EW
151my $cmd;
152for (my $i = 0; $i < @ARGV; $i++) {
153 if (defined $cmd{$ARGV[$i]}) {
154 $cmd = $ARGV[$i];
155 splice @ARGV, $i, 1;
156 last;
157 }
158};
159
448c81b4 160my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 161
b8c92cad 162read_repo_config(\%opts);
79bb8d88
EW
163my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
164 'version|V' => \$_version,
165 'id|i=s' => \$GIT_SVN);
166exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 167
dc5869c0 168set_default_vals();
3397f9df 169usage(0) if $_help;
551ce28f 170version() if $_version;
eeb0abe0 171usage(1) unless defined $cmd;
b8c92cad 172init_vars();
eeb0abe0 173load_authors() if $_authors;
bf78b1d8 174load_all_refs() if $_branch_all_refs;
dc62e25c 175svn_compat_check() unless $_use_lib;
7b520e62 176migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
3397f9df
EW
177$cmd{$cmd}->[0]->(@ARGV);
178exit 0;
179
180####################### primary functions ######################
181sub usage {
182 my $exit = shift || 0;
183 my $fd = $exit ? \*STDERR : \*STDOUT;
184 print $fd <<"";
185git-svn - bidirectional operations between a single Subversion tree and git
186Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
187
188 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
189
190 foreach (sort keys %cmd) {
448c81b4 191 next if $cmd && $cmd ne $_;
b203b769 192 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
193 foreach (keys %{$cmd{$_}->[2]}) {
194 # prints out arguments as they should be passed:
b8c92cad 195 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 196 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
197 "--$_" : "-$_" }
198 split /\|/,$_)," $x\n";
199 }
3397f9df
EW
200 }
201 print $fd <<"";
448c81b4
EW
202\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
203arbitrary identifier if you're tracking multiple SVN branches/repositories in
204one git repository and want to keep them separate. See git-svn(1) for more
205information.
3397f9df
EW
206
207 exit $exit;
208}
209
551ce28f
EW
210sub version {
211 print "git-svn version $VERSION\n";
212 exit 0;
213}
214
3397f9df 215sub rebuild {
1a82e793
EW
216 if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
217 copy_remote_ref();
218 }
3397f9df 219 $SVN_URL = shift or undef;
3397f9df 220 my $newest_rev = 0;
2beb3cdd
EW
221 if ($_upgrade) {
222 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
223 } else {
224 check_upgrade_needed();
225 }
3397f9df
EW
226
227 my $pid = open(my $rev_list,'-|');
228 defined $pid or croak $!;
229 if ($pid == 0) {
2beb3cdd 230 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
3397f9df 231 }
2beb3cdd 232 my $latest;
3397f9df
EW
233 while (<$rev_list>) {
234 chomp;
235 my $c = $_;
236 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
237 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
238 next if (!@commit); # skip merges
79bb8d88 239 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
e70dc780 240 if (!defined $rev || !$uuid) {
79bb8d88
EW
241 croak "Unable to extract revision or UUID from ",
242 "$c, $commit[$#commit]\n";
3397f9df 243 }
2beb3cdd
EW
244
245 # if we merged or otherwise started elsewhere, this is
246 # how we break out of it
1ca72aef 247 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
779b1446 248 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
2beb3cdd 249
2beb3cdd 250 unless (defined $latest) {
3397f9df
EW
251 if (!$SVN_URL && !$url) {
252 croak "SVN repository location required: $url\n";
253 }
254 $SVN_URL ||= $url;
1d52aba8
EW
255 $SVN_UUID ||= $uuid;
256 setup_git_svn();
2beb3cdd 257 $latest = $rev;
3397f9df 258 }
42d32870
EW
259 revdb_set($REVDB, $rev, $c);
260 print "r$rev = $c\n";
3397f9df
EW
261 $newest_rev = $rev if ($rev > $newest_rev);
262 }
263 close $rev_list or croak $?;
a5e0cedc
EW
264
265 goto out if $_use_lib;
3397f9df 266 if (!chdir $SVN_WC) {
1d52aba8 267 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
3397f9df
EW
268 chdir $SVN_WC or croak $!;
269 }
270
271 $pid = fork;
272 defined $pid or croak $!;
273 if ($pid == 0) {
274 my @svn_up = qw(svn up);
275 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
276 sys(@svn_up,"-r$newest_rev");
277 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
36f5b1f0 278 index_changes();
b8c92cad 279 exec('git-write-tree') or croak $!;
3397f9df
EW
280 }
281 waitpid $pid, 0;
b8c92cad 282 croak $? if $?;
a5e0cedc 283out:
2beb3cdd
EW
284 if ($_upgrade) {
285 print STDERR <<"";
286Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
287when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
288
289 }
3397f9df
EW
290}
291
292sub init {
03e0ea87 293 my $url = shift or die "SVN repository location required " .
81c5a0e6 294 "as a command-line argument\n";
03e0ea87
EW
295 $url =~ s!/+$!!; # strip trailing slash
296
297 if (my $repo_path = shift) {
298 unless (-d $repo_path) {
299 mkpath([$repo_path]);
300 }
301 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
302 init_vars();
303 }
304
305 $SVN_URL = $url;
3397f9df 306 unless (-d $GIT_DIR) {
f8ab6b73
EW
307 my @init_db = ('git-init-db');
308 push @init_db, "--template=$_template" if defined $_template;
309 push @init_db, "--shared" if defined $_shared;
310 sys(@init_db);
3397f9df
EW
311 }
312 setup_git_svn();
313}
314
315sub fetch {
2beb3cdd 316 check_upgrade_needed();
883d0a78 317 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
318 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
319 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
320 refs/heads/master^0))) {
321 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
322 }
323 return $ret;
324}
325
326sub fetch_cmd {
327 my (@parents) = @_;
3397f9df 328 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
defc6492
EW
329 unless ($_revision) {
330 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
3397f9df 331 }
defc6492 332 push @log_args, "-r$_revision";
3397f9df
EW
333 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
334
ce6f3519 335 my $svn_log = svn_log_raw(@log_args);
3397f9df 336
03823184 337 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
42d32870
EW
338 # don't need last_revision from grab_base_rev() because
339 # user could've specified a different revision to skip (they
340 # didn't want to import certain revisions into git for whatever
341 # reason, so trust $base->{revision} instead.
342 my (undef, $last_commit) = svn_grab_base_rev();
3397f9df 343 unless (-d $SVN_WC) {
1d52aba8 344 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
3397f9df 345 chdir $SVN_WC or croak $!;
1d52aba8 346 read_uuid();
3397f9df 347 $last_commit = git_commit($base, @parents);
36f5b1f0 348 assert_tree($last_commit);
3397f9df
EW
349 } else {
350 chdir $SVN_WC or croak $!;
1d52aba8 351 read_uuid();
6dfbe516
EW
352 # looks like a user manually cp'd and svn switch'ed
353 unless ($last_commit) {
354 sys(qw/svn revert -R ./);
355 assert_svn_wc_clean($base->{revision});
356 $last_commit = git_commit($base, @parents);
357 assert_tree($last_commit);
358 }
3397f9df
EW
359 }
360 my @svn_up = qw(svn up);
361 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
03823184
EW
362 my $last = $base;
363 while (my $log_msg = next_log_entry($svn_log)) {
03823184
EW
364 if ($last->{revision} >= $log_msg->{revision}) {
365 croak "Out of order: last >= current: ",
366 "$last->{revision} >= $log_msg->{revision}\n";
367 }
36f5b1f0
EW
368 # Revert is needed for cases like:
369 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
370 # I can't seem to reproduce something like that on a test...
371 sys(qw/svn revert -R ./);
372 assert_svn_wc_clean($last->{revision});
03823184 373 sys(@svn_up,"-r$log_msg->{revision}");
3397f9df 374 $last_commit = git_commit($log_msg, $last_commit, @parents);
03823184 375 $last = $log_msg;
3397f9df 376 }
b8c92cad 377 close $svn_log->{fh};
a5e0cedc 378 $last->{commit} = $last_commit;
03823184 379 return $last;
3397f9df
EW
380}
381
a5e0cedc
EW
382sub fetch_lib {
383 my (@parents) = @_;
384 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
747fa12c 385 $SVN ||= libsvn_connect($SVN_URL);
a5e0cedc
EW
386 my ($last_rev, $last_commit) = svn_grab_base_rev();
387 my ($base, $head) = libsvn_parse_revision($last_rev);
388 if ($base > $head) {
389 return { revision => $last_rev, commit => $last_commit }
390 }
391 my $index = set_index($GIT_SVN_INDEX);
392
393 # limit ourselves and also fork() since get_log won't release memory
394 # after processing a revision and SVN stuff seems to leak
395 my $inc = 1000;
396 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
397 read_uuid();
398 if (defined $last_commit) {
399 unless (-e $GIT_SVN_INDEX) {
400 sys(qw/git-read-tree/, $last_commit);
401 }
402 chomp (my $x = `git-write-tree`);
403 my ($y) = (`git-cat-file commit $last_commit`
404 =~ /^tree ($sha1)/m);
405 if ($y ne $x) {
406 unlink $GIT_SVN_INDEX or croak $!;
407 sys(qw/git-read-tree/, $last_commit);
408 }
409 chomp ($x = `git-write-tree`);
410 if ($y ne $x) {
411 print STDERR "trees ($last_commit) $y != $x\n",
412 "Something is seriously wrong...\n";
413 }
414 }
415 while (1) {
416 # fork, because using SVN::Pool with get_log() still doesn't
417 # seem to help enough to keep memory usage down.
418 defined(my $pid = fork) or croak $!;
419 if (!$pid) {
420 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
a5e0cedc
EW
421
422 # Yes I'm perfectly aware that the fourth argument
423 # below is the limit revisions number. Unfortunately
424 # performance sucks with it enabled, so it's much
425 # faster to fetch revision ranges instead of relying
426 # on the limiter.
747fa12c 427 libsvn_get_log(libsvn_dup_ra($SVN), [''],
dc62e25c 428 $min, $max, 0, 1, 1,
a5e0cedc
EW
429 sub {
430 my $log_msg;
431 if ($last_commit) {
432 $log_msg = libsvn_fetch(
433 $last_commit, @_);
434 $last_commit = git_commit(
435 $log_msg,
436 $last_commit,
437 @parents);
438 } else {
439 $log_msg = libsvn_new_tree(@_);
440 $last_commit = git_commit(
441 $log_msg, @parents);
442 }
443 });
a5e0cedc
EW
444 exit 0;
445 }
446 waitpid $pid, 0;
447 croak $? if $?;
448 ($last_rev, $last_commit) = svn_grab_base_rev();
449 last if ($max >= $head);
450 $min = $max + 1;
451 $max += $inc;
452 $max = $head if ($max > $head);
453 }
454 restore_index($index);
455 return { revision => $last_rev, commit => $last_commit };
456}
457
3397f9df
EW
458sub commit {
459 my (@commits) = @_;
2beb3cdd 460 check_upgrade_needed();
3397f9df
EW
461 if ($_stdin || !@commits) {
462 print "Reading from stdin...\n";
463 @commits = ();
464 while (<STDIN>) {
1ca72aef 465 if (/\b($sha1_short)\b/o) {
3397f9df
EW
466 unshift @commits, $1;
467 }
468 }
469 }
470 my @revs;
8de010ad
EW
471 foreach my $c (@commits) {
472 chomp(my @tmp = safe_qx('git-rev-parse',$c));
473 if (scalar @tmp == 1) {
474 push @revs, $tmp[0];
475 } elsif (scalar @tmp > 1) {
476 push @revs, reverse (safe_qx('git-rev-list',@tmp));
477 } else {
478 die "Failed to rev-parse $c\n";
479 }
3397f9df
EW
480 }
481 chomp @revs;
a5e0cedc
EW
482 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
483 print "Done committing ",scalar @revs," revisions to SVN\n";
484}
485
486sub commit_cmd {
487 my (@revs) = @_;
3397f9df 488
b63af9b3 489 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
1d52aba8 490 my $info = svn_info('.');
b63af9b3
EW
491 my $fetched = fetch();
492 if ($info->{Revision} != $fetched->{revision}) {
493 print STDERR "There are new revisions that were fetched ",
494 "and need to be merged (or acknowledged) ",
495 "before committing.\n";
496 exit 1;
497 }
498 $info = svn_info('.');
1d52aba8 499 read_uuid($info);
42d32870 500 my $last = $fetched;
3397f9df 501 foreach my $c (@revs) {
42d32870 502 my $mods = svn_checkout_tree($last, $c);
cf52b8f0
EW
503 if (scalar @$mods == 0) {
504 print "Skipping, no changes detected\n";
505 next;
506 }
42d32870 507 $last = svn_commit_tree($last, $c);
3397f9df 508 }
3397f9df
EW
509}
510
a5e0cedc
EW
511sub commit_lib {
512 my (@revs) = @_;
513 my ($r_last, $cmt_last) = svn_grab_base_rev();
514 defined $r_last or die "Must have an existing revision to commit\n";
cf7424b0 515 my $fetched = fetch();
a5e0cedc
EW
516 if ($r_last != $fetched->{revision}) {
517 print STDERR "There are new revisions that were fetched ",
518 "and need to be merged (or acknowledged) ",
519 "before committing.\n",
520 "last rev: $r_last\n",
521 " current: $fetched->{revision}\n";
522 exit 1;
523 }
524 read_uuid();
525 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
526 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
527
5a990e45 528 my $repo;
27e9fb8d 529 set_svn_commit_env();
a5e0cedc 530 foreach my $c (@revs) {
ec9d00d0
EW
531 my $log_msg = get_commit_message($c, $commit_msg);
532
a5e0cedc
EW
533 # fork for each commit because there's a memory leak I
534 # can't track down... (it's probably in the SVN code)
535 defined(my $pid = open my $fh, '-|') or croak $!;
536 if (!$pid) {
a5e0cedc
EW
537 my $ed = SVN::Git::Editor->new(
538 { r => $r_last,
747fa12c 539 ra => libsvn_dup_ra($SVN),
a5e0cedc 540 c => $c,
747fa12c 541 svn_path => $SVN->{svn_path},
a5e0cedc
EW
542 },
543 $SVN->get_commit_editor(
544 $log_msg->{msg},
545 sub {
546 libsvn_commit_cb(
547 @_, $c,
548 $log_msg->{msg},
549 $r_last,
550 $cmt_last)
551 },
552 @lock)
553 );
42d32870 554 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
a5e0cedc
EW
555 if (@$mods == 0) {
556 print "No changes\nr$r_last = $cmt_last\n";
557 $ed->abort_edit;
558 } else {
559 $ed->close_edit;
560 }
561 exit 0;
562 }
563 my ($r_new, $cmt_new, $no);
564 while (<$fh>) {
565 print $_;
566 chomp;
567 if (/^r(\d+) = ($sha1)$/o) {
568 ($r_new, $cmt_new) = ($1, $2);
569 } elsif ($_ eq 'No changes') {
570 $no = 1;
571 }
572 }
d25c26e7 573 close $fh or exit 1;
a5e0cedc
EW
574 if (! defined $r_new && ! defined $cmt_new) {
575 unless ($no) {
576 die "Failed to parse revision information\n";
577 }
578 } else {
579 ($r_last, $cmt_last) = ($r_new, $cmt_new);
580 }
581 }
ec9d00d0 582 $ENV{LC_ALL} = 'C';
a5e0cedc
EW
583 unlink $commit_msg;
584}
8f22562c 585
b22d4497
EW
586sub dcommit {
587 my $gs = "refs/remotes/$GIT_SVN";
588 chomp(my @refs = safe_qx(qw/git-rev-list --no-merges/, "$gs..HEAD"));
45bf473a 589 my $last_rev;
b22d4497 590 foreach my $d (reverse @refs) {
48d044b5
EW
591 if (quiet_run('git-rev-parse','--verify',"$d~1") != 0) {
592 die "Commit $d\n",
593 "has no parent commit, and therefore ",
594 "nothing to diff against.\n",
595 "You should be working from a repository ",
596 "originally created by git-svn\n";
597 }
45bf473a
EW
598 unless (defined $last_rev) {
599 (undef, $last_rev, undef) = cmt_metadata("$d~1");
600 unless (defined $last_rev) {
601 die "Unable to extract revision information ",
602 "from commit $d~1\n";
603 }
604 }
b22d4497
EW
605 if ($_dry_run) {
606 print "diff-tree $d~1 $d\n";
607 } else {
45bf473a
EW
608 if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
609 $last_rev = $r;
610 } # else: no changes, same $last_rev
b22d4497
EW
611 }
612 }
613 return if $_dry_run;
614 fetch();
615 my @diff = safe_qx(qw/git-diff-tree HEAD/, $gs);
616 my @finish;
617 if (@diff) {
618 @finish = qw/rebase/;
619 push @finish, qw/--merge/ if $_merge;
620 push @finish, "--strategy=$_strategy" if $_strategy;
621 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
622 } else {
623 print "No changes between current HEAD and $gs\n",
624 "Hard resetting to the latest $gs\n";
4769489a 625 @finish = qw/reset --mixed/;
b22d4497
EW
626 }
627 sys('git', @finish, $gs);
628}
629
a5e0cedc 630sub show_ignore {
883d0a78 631 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
a5e0cedc
EW
632 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
633}
634
635sub show_ignore_cmd {
636 require File::Find or die $!;
637 if (defined $_revision) {
638 die "-r/--revision option doesn't work unless the Perl SVN ",
639 "libraries are used\n";
640 }
8f22562c
EW
641 chdir $SVN_WC or croak $!;
642 my %ign;
643 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
644 s#^\./##;
8a97e368 645 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
8f22562c
EW
646 }}, no_chdir=>1},'.');
647
648 print "\n# /\n";
649 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
650 delete $ign{'.'};
651 foreach my $i (sort keys %ign) {
652 print "\n# ",$i,"\n";
653 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
654 }
655}
656
a5e0cedc
EW
657sub show_ignore_lib {
658 my $repo;
747fa12c 659 $SVN ||= libsvn_connect($SVN_URL);
a5e0cedc 660 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
747fa12c 661 libsvn_traverse_ignore(\*STDOUT, $SVN->{svn_path}, $r);
a5e0cedc
EW
662}
663
9d55b41a
EW
664sub graft_branches {
665 my $gr_file = "$GIT_DIR/info/grafts";
666 my ($grafts, $comments) = read_grafts($gr_file);
667 my $gr_sha1;
668
669 if (%$grafts) {
670 # temporarily disable our grafts file to make this idempotent
671 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
672 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
673 }
674
675 my $l_map = read_url_paths();
676 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
677 unless ($_no_default_regex) {
c1927a85
EW
678 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
679 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
680 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
9d55b41a
EW
681 }
682 foreach my $u (keys %$l_map) {
683 if (@re) {
684 foreach my $p (keys %{$l_map->{$u}}) {
c1927a85 685 graft_merge_msg($grafts,$l_map,$u,$p,@re);
9d55b41a
EW
686 }
687 }
a5e0cedc
EW
688 unless ($_no_graft_copy) {
689 if ($_use_lib) {
690 graft_file_copy_lib($grafts,$l_map,$u);
691 } else {
692 graft_file_copy_cmd($grafts,$l_map,$u);
693 }
694 }
9d55b41a 695 }
c1927a85 696 graft_tree_joins($grafts);
9d55b41a
EW
697
698 write_grafts($grafts, $comments, $gr_file);
699 unlink "$gr_file~$gr_sha1" if $gr_sha1;
700}
701
702sub multi_init {
703 my $url = shift;
704 $_trunk ||= 'trunk';
705 $_trunk =~ s#/+$##;
706 $url =~ s#/+$## if $url;
707 if ($_trunk !~ m#^[a-z\+]+://#) {
708 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
709 unless ($url) {
710 print STDERR "E: '$_trunk' is not a complete URL ",
711 "and a separate URL is not specified\n";
712 exit 1;
713 }
714 $_trunk = $url . $_trunk;
715 }
c35b96e7 716 my $ch_id;
9d55b41a 717 if ($GIT_SVN eq 'git-svn') {
c35b96e7 718 $ch_id = 1;
9d55b41a
EW
719 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
720 }
721 init_vars();
c35b96e7
EW
722 unless (-d $GIT_SVN_DIR) {
723 print "GIT_SVN_ID set to 'trunk' for $_trunk\n" if $ch_id;
724 init($_trunk);
725 sys('git-repo-config', 'svn.trunk', $_trunk);
726 }
9d55b41a
EW
727 complete_url_ls_init($url, $_branches, '--branches/-b', '');
728 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
729}
730
731sub multi_fetch {
732 # try to do trunk first, since branches/tags
733 # may be descended from it.
cf7424b0
EW
734 if (-e "$GIT_DIR/svn/trunk/info/url") {
735 fetch_child_id('trunk', @_);
9d55b41a
EW
736 }
737 rec_fetch('', "$GIT_DIR/svn", @_);
738}
739
79bb8d88
EW
740sub show_log {
741 my (@args) = @_;
742 my ($r_min, $r_max);
743 my $r_last = -1; # prevent dupes
744 rload_authors() if $_authors;
745 if (defined $TZ) {
746 $ENV{TZ} = $TZ;
747 } else {
748 delete $ENV{TZ};
749 }
750 if (defined $_revision) {
751 if ($_revision =~ /^(\d+):(\d+)$/) {
752 ($r_min, $r_max) = ($1, $2);
753 } elsif ($_revision =~ /^\d+$/) {
754 $r_min = $r_max = $_revision;
755 } else {
756 print STDERR "-r$_revision is not supported, use ",
757 "standard \'git log\' arguments instead\n";
758 exit 1;
759 }
760 }
761
762 my $pid = open(my $log,'-|');
763 defined $pid or croak $!;
764 if (!$pid) {
c0d48222 765 exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
79bb8d88
EW
766 }
767 setup_pager();
768 my (@k, $c, $d);
c0d48222 769
79bb8d88
EW
770 while (<$log>) {
771 if (/^commit ($sha1_short)/o) {
772 my $cmt = $1;
c0d48222 773 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
79bb8d88
EW
774 $r_last = $c->{r};
775 process_commit($c, $r_min, $r_max, \@k) or
776 goto out;
777 }
778 $d = undef;
779 $c = { c => $cmt };
780 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
781 get_author_info($c, $1, $2, $3);
782 } elsif (/^(?:tree|parent|committer) /) {
783 # ignore
784 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
785 push @{$c->{raw}}, $_;
74a31a10 786 } elsif (/^[ACRMDT]\t/) {
747fa12c 787 # we could add $SVN->{svn_path} here, but that requires
74a31a10
EW
788 # remote access at the moment (repo_path_split)...
789 s#^([ACRMDT])\t# $1 #;
790 push @{$c->{changed}}, $_;
79bb8d88
EW
791 } elsif (/^diff /) {
792 $d = 1;
793 push @{$c->{diff}}, $_;
794 } elsif ($d) {
795 push @{$c->{diff}}, $_;
796 } elsif (/^ (git-svn-id:.+)$/) {
74a31a10 797 ($c->{url}, $c->{r}, undef) = extract_metadata($1);
79bb8d88
EW
798 } elsif (s/^ //) {
799 push @{$c->{l}}, $_;
800 }
801 }
802 if ($c && defined $c->{r} && $c->{r} != $r_last) {
803 $r_last = $c->{r};
804 process_commit($c, $r_min, $r_max, \@k);
805 }
806 if (@k) {
807 my $swap = $r_max;
808 $r_max = $r_min;
809 $r_min = $swap;
810 process_commit($_, $r_min, $r_max) foreach reverse @k;
811 }
812out:
813 close $log;
814 print '-' x72,"\n" unless $_incremental || $_oneline;
815}
816
27e9fb8d
EW
817sub commit_diff_usage {
818 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
819 exit 1
820}
821
822sub commit_diff {
823 if (!$_use_lib) {
824 print STDERR "commit-diff must be used with SVN libraries\n";
825 exit 1;
826 }
827 my $ta = shift or commit_diff_usage();
828 my $tb = shift or commit_diff_usage();
829 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
830 print STDERR "Needed URL or usable git-svn id command-line\n";
831 commit_diff_usage();
832 }
e70dc780
EW
833 my $r = shift;
834 unless (defined $r) {
835 if (defined $_revision) {
836 $r = $_revision
837 } else {
838 die "-r|--revision is a required argument\n";
839 }
840 }
27e9fb8d
EW
841 if (defined $_message && defined $_file) {
842 print STDERR "Both --message/-m and --file/-F specified ",
843 "for the commit message.\n",
844 "I have no idea what you mean\n";
845 exit 1;
846 }
847 if (defined $_file) {
4ad4515d 848 $_message = file_to_s($_file);
27e9fb8d
EW
849 } else {
850 $_message ||= get_commit_message($tb,
851 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
852 }
747fa12c 853 $SVN ||= libsvn_connect($SVN_URL);
45bf473a
EW
854 if ($r eq 'HEAD') {
855 $r = $SVN->get_latest_revnum;
856 } elsif ($r !~ /^\d+$/) {
857 die "revision argument: $r not understood by git-svn\n";
858 }
27e9fb8d 859 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
45bf473a
EW
860 my $rev_committed;
861 my $ed = SVN::Git::Editor->new({ r => $r,
747fa12c
EW
862 ra => libsvn_dup_ra($SVN),
863 c => $tb,
864 svn_path => $SVN->{svn_path}
27e9fb8d
EW
865 },
866 $SVN->get_commit_editor($_message,
45bf473a
EW
867 sub {
868 $rev_committed = $_[0];
869 print "Committed $_[0]\n";
870 }, @lock)
27e9fb8d 871 );
d25c26e7
EW
872 eval {
873 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
874 if (@$mods == 0) {
875 print "No changes\n$ta == $tb\n";
876 $ed->abort_edit;
877 } else {
878 $ed->close_edit;
879 }
880 };
881 fatal "$@\n" if $@;
5f641ccc 882 $_message = $_file = undef;
45bf473a 883 return $rev_committed;
27e9fb8d
EW
884}
885
3397f9df
EW
886########################### utility functions #########################
887
c0d48222
EW
888sub cmt_showable {
889 my ($c) = @_;
890 return 1 if defined $c->{r};
891 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
892 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
893 my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
894 shift @msg while ($msg[0] ne "\n");
895 shift @msg;
896 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
897
898 (undef, $c->{r}, undef) = extract_metadata(
899 (grep(/^git-svn-id: /, @msg))[-1]);
900 }
901 return defined $c->{r};
902}
903
904sub git_svn_log_cmd {
905 my ($r_min, $r_max) = @_;
906 my @cmd = (qw/git-log --abbrev-commit --pretty=raw
907 --default/, "refs/remotes/$GIT_SVN");
74a31a10
EW
908 push @cmd, '-r' unless $_non_recursive;
909 push @cmd, qw/--raw --name-status/ if $_verbose;
c0d48222
EW
910 return @cmd unless defined $r_max;
911 if ($r_max == $r_min) {
912 push @cmd, '--max-count=1';
913 if (my $c = revdb_get($REVDB, $r_max)) {
914 push @cmd, $c;
915 }
916 } else {
917 my ($c_min, $c_max);
918 $c_max = revdb_get($REVDB, $r_max);
919 $c_min = revdb_get($REVDB, $r_min);
74a31a10 920 if (defined $c_min && defined $c_max) {
c0d48222
EW
921 if ($r_max > $r_max) {
922 push @cmd, "$c_min..$c_max";
923 } else {
924 push @cmd, "$c_max..$c_min";
925 }
926 } elsif ($r_max > $r_min) {
927 push @cmd, $c_max;
928 } else {
929 push @cmd, $c_min;
930 }
931 }
932 return @cmd;
933}
934
cf7424b0
EW
935sub fetch_child_id {
936 my $id = shift;
937 print "Fetching $id\n";
938 my $ref = "$GIT_DIR/refs/remotes/$id";
a00439ac 939 defined(my $pid = open my $fh, '-|') or croak $!;
cf7424b0 940 if (!$pid) {
a00439ac 941 $_repack = undef;
cf7424b0
EW
942 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
943 init_vars();
944 fetch(@_);
945 exit 0;
946 }
cf7424b0 947 while (<$fh>) {
a00439ac
EW
948 print $_;
949 check_repack() if (/^r\d+ = $sha1/);
cf7424b0 950 }
a00439ac 951 close $fh or croak $?;
cf7424b0
EW
952}
953
9d55b41a
EW
954sub rec_fetch {
955 my ($pfx, $p, @args) = @_;
956 my @dir;
957 foreach (sort <$p/*>) {
958 if (-r "$_/info/url") {
959 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
960 my $id = $pfx . basename $_;
961 next if $id eq 'trunk';
cf7424b0 962 fetch_child_id($id, @args);
9d55b41a
EW
963 } elsif (-d $_) {
964 push @dir, $_;
965 }
966 }
967 foreach (@dir) {
968 my $x = $_;
969 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
970 rec_fetch($x, $_);
971 }
972}
973
974sub complete_url_ls_init {
975 my ($url, $var, $switch, $pfx) = @_;
976 unless ($var) {
977 print STDERR "W: $switch not specified\n";
978 return;
979 }
980 $var =~ s#/+$##;
981 if ($var !~ m#^[a-z\+]+://#) {
982 $var = '/' . $var if ($var !~ m#^/#);
983 unless ($url) {
984 print STDERR "E: '$var' is not a complete URL ",
985 "and a separate URL is not specified\n";
986 exit 1;
987 }
988 $var = $url . $var;
989 }
a5e0cedc
EW
990 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
991 : safe_qx(qw/svn ls --non-interactive/, $var));
9d55b41a
EW
992 my $old = $GIT_SVN;
993 defined(my $pid = fork) or croak $!;
994 if (!$pid) {
995 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
996 $u =~ s#/+$##;
997 if ($u !~ m!\Q$var\E/(.+)$!) {
998 print STDERR "W: Unrecognized URL: $u\n";
999 die "This should never happen\n";
1000 }
c35b96e7 1001 # don't try to init already existing refs
9d55b41a 1002 my $id = $pfx.$1;
9d55b41a
EW
1003 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1004 init_vars();
c35b96e7
EW
1005 unless (-d $GIT_SVN_DIR) {
1006 print "init $u => $id\n";
1007 init($u);
1008 }
9d55b41a
EW
1009 }
1010 exit 0;
1011 }
1012 waitpid $pid, 0;
1013 croak $? if $?;
c35b96e7
EW
1014 my ($n) = ($switch =~ /^--(\w+)/);
1015 sys('git-repo-config', "svn.$n", $var);
9d55b41a
EW
1016}
1017
1018sub common_prefix {
1019 my $paths = shift;
1020 my %common;
1021 foreach (@$paths) {
1022 my @tmp = split m#/#, $_;
1023 my $p = '';
1024 while (my $x = shift @tmp) {
1025 $p .= "/$x";
1026 $common{$p} ||= 0;
1027 $common{$p}++;
1028 }
1029 }
1030 foreach (sort {length $b <=> length $a} keys %common) {
1031 if ($common{$_} == @$paths) {
1032 return $_;
1033 }
1034 }
1035 return '';
1036}
1037
c1927a85
EW
1038# grafts set here are 'stronger' in that they're based on actual tree
1039# matches, and won't be deleted from merge-base checking in write_grafts()
1040sub graft_tree_joins {
1041 my $grafts = shift;
1042 map_tree_joins() if (@_branch_from && !%tree_map);
1043 return unless %tree_map;
1044
1045 git_svn_each(sub {
1046 my $i = shift;
1047 defined(my $pid = open my $fh, '-|') or croak $!;
1048 if (!$pid) {
1049 exec qw/git-rev-list --pretty=raw/,
1050 "refs/remotes/$i" or croak $!;
1051 }
1052 while (<$fh>) {
1053 next unless /^commit ($sha1)$/o;
1054 my $c = $1;
1055 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
1056 next unless $tree_map{$t};
1057
1058 my $l;
1059 do {
1060 $l = readline $fh;
1061 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
1062
1063 my ($s, $tz) = ($1, $2);
1064 if ($tz =~ s/^\+//) {
1065 $s += tz_to_s_offset($tz);
1066 } elsif ($tz =~ s/^\-//) {
1067 $s -= tz_to_s_offset($tz);
1068 }
1069
1070 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
1071
1072 foreach my $p (@{$tree_map{$t}}) {
1073 next if $p eq $c;
1074 my $mb = eval {
1075 safe_qx('git-merge-base', $c, $p)
1076 };
1077 next unless ($@ || $?);
1078 if (defined $r_a) {
1079 # see if SVN says it's a relative
1080 my ($url_b, $r_b, $uuid_b) =
1081 cmt_metadata($p);
1082 next if (defined $url_b &&
1083 defined $url_a &&
1084 ($url_a eq $url_b) &&
1085 ($uuid_a eq $uuid_b));
1086 if ($uuid_a eq $uuid_b) {
1087 if ($r_b < $r_a) {
1088 $grafts->{$c}->{$p} = 2;
1089 next;
1090 } elsif ($r_b > $r_a) {
1091 $grafts->{$p}->{$c} = 2;
1092 next;
1093 }
1094 }
1095 }
1096 my $ct = get_commit_time($p);
1097 if ($ct < $s) {
1098 $grafts->{$c}->{$p} = 2;
1099 } elsif ($ct > $s) {
1100 $grafts->{$p}->{$c} = 2;
1101 }
1102 # what should we do when $ct == $s ?
1103 }
1104 }
1105 close $fh or croak $?;
1106 });
1107}
1108
9d55b41a 1109# this isn't funky-filename safe, but good enough for now...
a5e0cedc 1110sub graft_file_copy_cmd {
9d55b41a
EW
1111 my ($grafts, $l_map, $u) = @_;
1112 my $paths = $l_map->{$u};
1113 my $pfx = common_prefix([keys %$paths]);
42d32870 1114 $SVN_URL ||= $u.$pfx;
9d55b41a
EW
1115 my $pid = open my $fh, '-|';
1116 defined $pid or croak $!;
1117 unless ($pid) {
a5e0cedc
EW
1118 my @exec = qw/svn log -v/;
1119 push @exec, "-r$_revision" if defined $_revision;
1120 exec @exec, $u.$pfx or croak $!;
9d55b41a
EW
1121 }
1122 my ($r, $mp) = (undef, undef);
1123 while (<$fh>) {
1124 chomp;
1125 if (/^\-{72}$/) {
1126 $mp = $r = undef;
1127 } elsif (/^r(\d+) \| /) {
1128 $r = $1 unless defined $r;
1129 } elsif (/^Changed paths:/) {
1130 $mp = 1;
1131 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
9d55b41a 1132 my ($p1, $p0, $r0) = ($1, $2, $3);
a5e0cedc 1133 my $c = find_graft_path_commit($paths, $p1, $r);
9d55b41a 1134 next unless $c;
a5e0cedc 1135 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
9d55b41a
EW
1136 }
1137 }
1138}
1139
a5e0cedc
EW
1140sub graft_file_copy_lib {
1141 my ($grafts, $l_map, $u) = @_;
1142 my $tree_paths = $l_map->{$u};
1143 my $pfx = common_prefix([keys %$tree_paths]);
1144 my ($repo, $path) = repo_path_split($u.$pfx);
747fa12c 1145 $SVN = libsvn_connect($repo);
a5e0cedc
EW
1146
1147 my ($base, $head) = libsvn_parse_revision();
1148 my $inc = 1000;
1149 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
42d32870
EW
1150 my $eh = $SVN::Error::handler;
1151 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
a5e0cedc
EW
1152 while (1) {
1153 my $pool = SVN::Pool->new;
747fa12c
EW
1154 libsvn_get_log(libsvn_dup_ra($SVN), [$path],
1155 $min, $max, 0, 1, 1,
a5e0cedc
EW
1156 sub {
1157 libsvn_graft_file_copies($grafts, $tree_paths,
1158 $path, @_);
1159 }, $pool);
1160 $pool->clear;
1161 last if ($max >= $head);
1162 $min = $max + 1;
1163 $max += $inc;
1164 $max = $head if ($max > $head);
1165 }
42d32870 1166 $SVN::Error::handler = $eh;
a5e0cedc
EW
1167}
1168
9d55b41a
EW
1169sub process_merge_msg_matches {
1170 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1171 my (@strong, @weak);
1172 foreach (@matches) {
1173 # merging with ourselves is not interesting
1174 next if $_ eq $p;
1175 if ($l_map->{$u}->{$_}) {
1176 push @strong, $_;
1177 } else {
1178 push @weak, $_;
1179 }
1180 }
1181 foreach my $w (@weak) {
1182 last if @strong;
1183 # no exact match, use branch name as regexp.
1184 my $re = qr/\Q$w\E/i;
1185 foreach (keys %{$l_map->{$u}}) {
1186 if (/$re/) {
c1927a85 1187 push @strong, $l_map->{$u}->{$_};
9d55b41a
EW
1188 last;
1189 }
1190 }
1191 last if @strong;
1192 $w = basename($w);
1193 $re = qr/\Q$w\E/i;
1194 foreach (keys %{$l_map->{$u}}) {
1195 if (/$re/) {
c1927a85 1196 push @strong, $l_map->{$u}->{$_};
9d55b41a
EW
1197 last;
1198 }
1199 }
1200 }
1201 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1202 \s(?:[a-f\d\-]+)$/xsm);
1203 unless (defined $rev) {
1204 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1205 \@(?:[a-f\d\-]+)/xsm);
1206 return unless defined $rev;
1207 }
1208 foreach my $m (@strong) {
c1927a85 1209 my ($r0, $s0) = find_rev_before($rev, $m, 1);
9d55b41a
EW
1210 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1211 }
1212}
1213
1214sub graft_merge_msg {
1215 my ($grafts, $l_map, $u, $p, @re) = @_;
1216
1217 my $x = $l_map->{$u}->{$p};
1218 my $rl = rev_list_raw($x);
1219 while (my $c = next_rev_list_entry($rl)) {
1220 foreach my $re (@re) {
1221 my (@br) = ($c->{m} =~ /$re/g);
1222 next unless @br;
1223 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1224 }
1225 }
1226}
1227
1d52aba8
EW
1228sub read_uuid {
1229 return if $SVN_UUID;
a5e0cedc
EW
1230 if ($_use_lib) {
1231 my $pool = SVN::Pool->new;
1232 $SVN_UUID = $SVN->get_uuid($pool);
1233 $pool->clear;
1234 } else {
1235 my $info = shift || svn_info('.');
1236 $SVN_UUID = $info->{'Repository UUID'} or
1d52aba8 1237 croak "Repository UUID unreadable\n";
a5e0cedc 1238 }
883d0a78
EW
1239}
1240
1241sub quiet_run {
1242 my $pid = fork;
1243 defined $pid or croak $!;
1244 if (!$pid) {
1245 open my $null, '>', '/dev/null' or croak $!;
1246 open STDERR, '>&', $null or croak $!;
1247 open STDOUT, '>&', $null or croak $!;
1248 exec @_ or croak $!;
1249 }
1250 waitpid $pid, 0;
1251 return $?;
1252}
1253
1254sub repo_path_split {
1255 my $full_url = shift;
1256 $full_url =~ s#/+$##;
1257
1258 foreach (@repo_path_split_cache) {
1259 if ($full_url =~ s#$_##) {
1260 my $u = $1;
1261 $full_url =~ s#^/+##;
1262 return ($u, $full_url);
1263 }
1264 }
a5e0cedc 1265 if ($_use_lib) {
a69a165f 1266 my $tmp = libsvn_connect($full_url);
747fa12c 1267 return ($tmp->{repos_root}, $tmp->{svn_path});
a5e0cedc 1268 } else {
a69a165f
EW
1269 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1270 $path =~ s#^/+##;
1271 my @paths = split(m#/+#, $path);
a5e0cedc
EW
1272 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1273 my $n = shift @paths || last;
1274 $url .= "/$n";
1275 }
a69a165f
EW
1276 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1277 $path = join('/',@paths);
1278 return ($url, $path);
883d0a78 1279 }
1d52aba8
EW
1280}
1281
3397f9df
EW
1282sub setup_git_svn {
1283 defined $SVN_URL or croak "SVN repository location required\n";
1284 unless (-d $GIT_DIR) {
1285 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1286 }
883d0a78
EW
1287 mkpath([$GIT_SVN_DIR]);
1288 mkpath(["$GIT_SVN_DIR/info"]);
42d32870
EW
1289 open my $fh, '>>',$REVDB or croak $!;
1290 close $fh;
883d0a78 1291 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
3397f9df 1292
3397f9df
EW
1293}
1294
1295sub assert_svn_wc_clean {
a5e0cedc 1296 return if $_use_lib;
36f5b1f0 1297 my ($svn_rev) = @_;
3397f9df 1298 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
ce4c8b24
EW
1299 my $lcr = svn_info('.')->{'Last Changed Rev'};
1300 if ($svn_rev != $lcr) {
1301 print STDERR "Checking for copy-tree ... ";
ce4c8b24
EW
1302 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1303 "-r$lcr:$svn_rev")));
1304 if (@diff) {
1305 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1306 } else {
1307 print STDERR "OK!\n";
1308 }
3397f9df
EW
1309 }
1310 my @status = grep(!/^Performing status on external/,(`svn status`));
1311 @status = grep(!/^\s*$/,@status);
191414c0 1312 @status = grep(!/^X/,@status) if $_no_ignore_ext;
3397f9df
EW
1313 if (scalar @status) {
1314 print STDERR "Tree ($SVN_WC) is not clean:\n";
1315 print STDERR $_ foreach @status;
1316 croak;
1317 }
cf52b8f0
EW
1318}
1319
a5e0cedc 1320sub get_tree_from_treeish {
cf52b8f0
EW
1321 my ($treeish) = @_;
1322 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1323 chomp(my $type = `git-cat-file -t $treeish`);
1324 my $expected;
1325 while ($type eq 'tag') {
1326 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1327 }
1328 if ($type eq 'commit') {
1329 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1330 ($expected) = ($expected =~ /^tree ($sha1)$/);
1331 die "Unable to get tree from $treeish\n" unless $expected;
1332 } elsif ($type eq 'tree') {
1333 $expected = $treeish;
1334 } else {
1335 die "$treeish is a $type, expected tree, tag or commit\n";
1336 }
a5e0cedc
EW
1337 return $expected;
1338}
1339
1340sub assert_tree {
1341 return if $_use_lib;
1342 my ($treeish) = @_;
1343 my $expected = get_tree_from_treeish($treeish);
cf52b8f0 1344
cf52b8f0
EW
1345 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1346 if (-e $tmpindex) {
1347 unlink $tmpindex or croak $!;
1348 }
a5e0cedc 1349 my $old_index = set_index($tmpindex);
36f5b1f0 1350 index_changes(1);
cf52b8f0 1351 chomp(my $tree = `git-write-tree`);
a5e0cedc 1352 restore_index($old_index);
cf52b8f0
EW
1353 if ($tree ne $expected) {
1354 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
3397f9df 1355 }
36f5b1f0 1356 unlink $tmpindex;
3397f9df
EW
1357}
1358
1359sub parse_diff_tree {
1360 my $diff_fh = shift;
1361 local $/ = "\0";
1362 my $state = 'meta';
1363 my @mods;
1364 while (<$diff_fh>) {
1365 chomp $_; # this gets rid of the trailing "\0"
3397f9df
EW
1366 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1367 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1368 push @mods, { mode_a => $1, mode_b => $2,
1369 sha1_b => $3, chg => $4 };
1370 if ($4 =~ /^(?:C|R)$/) {
1371 $state = 'file_a';
1372 } else {
1373 $state = 'file_b';
1374 }
1375 } elsif ($state eq 'file_a') {
cf52b8f0 1376 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1377 if ($x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1378 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1379 }
1380 $x->{file_a} = $_;
1381 $state = 'file_b';
1382 } elsif ($state eq 'file_b') {
cf52b8f0 1383 my $x = $mods[$#mods] or croak "Empty array\n";
3397f9df 1384 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
cf52b8f0 1385 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1386 }
1387 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
cf52b8f0 1388 croak "Error parsing $_, $x->{chg}\n";
3397f9df
EW
1389 }
1390 $x->{file_b} = $_;
1391 $state = 'meta';
1392 } else {
cf52b8f0 1393 croak "Error parsing $_\n";
3397f9df
EW
1394 }
1395 }
cf7424b0 1396 close $diff_fh or croak $?;
cf52b8f0 1397
3397f9df
EW
1398 return \@mods;
1399}
1400
1401sub svn_check_prop_executable {
1402 my $m = shift;
cf52b8f0
EW
1403 return if -l $m->{file_b};
1404 if ($m->{mode_b} =~ /755$/) {
1405 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1406 if ($m->{mode_a} !~ /755$/) {
1407 sys(qw(svn propset svn:executable 1), $m->{file_b});
1408 }
1409 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
3397f9df
EW
1410 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1411 sys(qw(svn propdel svn:executable), $m->{file_b});
cf52b8f0
EW
1412 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1413 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
3397f9df
EW
1414 }
1415}
1416
1417sub svn_ensure_parent_path {
1418 my $dir_b = dirname(shift);
1419 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1420 mkpath([$dir_b]) unless (-d $dir_b);
1421 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1422}
1423
cf52b8f0
EW
1424sub precommit_check {
1425 my $mods = shift;
1426 my (%rm_file, %rmdir_check, %added_check);
1427
1428 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1429 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1430 if ($m->{chg} eq 'R') {
1431 if (-d $m->{file_b}) {
1432 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1433 }
1434 # dir/$file => dir/file/$file
1435 my $dirname = dirname($m->{file_b});
1436 while ($dirname ne File::Spec->curdir) {
1437 if ($dirname ne $m->{file_a}) {
1438 $dirname = dirname($dirname);
1439 next;
1440 }
1441 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1442 }
1443 # baz/zzz => baz (baz is a file)
1444 $dirname = dirname($m->{file_a});
1445 while ($dirname ne File::Spec->curdir) {
1446 if ($dirname ne $m->{file_b}) {
1447 $dirname = dirname($dirname);
1448 next;
1449 }
1450 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1451 }
1452 }
1453 if ($m->{chg} =~ /^(D|R)$/) {
1454 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1455 $rm_file{ $m->{$t} } = 1;
1456 my $dirname = dirname( $m->{$t} );
1457 my $basename = basename( $m->{$t} );
1458 $rmdir_check{$dirname}->{$basename} = 1;
1459 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1460 if (-d $m->{file_b}) {
1461 err_dir_to_file($m->{file_b});
1462 }
1463 my $dirname = dirname( $m->{file_b} );
1464 my $basename = basename( $m->{file_b} );
1465 $added_check{$dirname}->{$basename} = 1;
1466 while ($dirname ne File::Spec->curdir) {
1467 if ($rm_file{$dirname}) {
1468 err_file_to_dir($m->{file_b});
1469 }
1470 $dirname = dirname $dirname;
1471 }
1472 }
1473 }
1474 return (\%rmdir_check, \%added_check);
1475
1476 sub err_dir_to_file {
1477 my $file = shift;
1478 print STDERR "Node change from directory to file ",
1479 "is not supported by Subversion: ",$file,"\n";
1480 exit 1;
1481 }
1482 sub err_file_to_dir {
1483 my $file = shift;
1484 print STDERR "Node change from file to directory ",
1485 "is not supported by Subversion: ",$file,"\n";
1486 exit 1;
1487 }
1488}
1489
a5e0cedc
EW
1490
1491sub get_diff {
42d32870 1492 my ($from, $treeish) = @_;
36f5b1f0 1493 assert_tree($from);
ac8e0b91 1494 print "diff-tree $from $treeish\n";
3397f9df
EW
1495 my $pid = open my $diff_fh, '-|';
1496 defined $pid or croak $!;
1497 if ($pid == 0) {
162f4129
EW
1498 my @diff_tree = qw(git-diff-tree -z -r);
1499 if ($_cp_similarity) {
1500 push @diff_tree, "-C$_cp_similarity";
1501 } else {
1502 push @diff_tree, '-C';
1503 }
72942938
EW
1504 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1505 push @diff_tree, "-l$_l" if defined $_l;
cf52b8f0 1506 exec(@diff_tree, $from, $treeish) or croak $!;
3397f9df 1507 }
a5e0cedc
EW
1508 return parse_diff_tree($diff_fh);
1509}
1510
1511sub svn_checkout_tree {
42d32870
EW
1512 my ($from, $treeish) = @_;
1513 my $mods = get_diff($from->{commit}, $treeish);
a5e0cedc 1514 return $mods unless (scalar @$mods);
cf52b8f0
EW
1515 my ($rm, $add) = precommit_check($mods);
1516
1517 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1518 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3397f9df
EW
1519 if ($m->{chg} eq 'C') {
1520 svn_ensure_parent_path( $m->{file_b} );
1521 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
cf52b8f0 1522 apply_mod_line_blob($m);
3397f9df
EW
1523 svn_check_prop_executable($m);
1524 } elsif ($m->{chg} eq 'D') {
3397f9df
EW
1525 sys(qw(svn rm --force), $m->{file_b});
1526 } elsif ($m->{chg} eq 'R') {
1527 svn_ensure_parent_path( $m->{file_b} );
1528 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
cf52b8f0 1529 apply_mod_line_blob($m);
3397f9df 1530 svn_check_prop_executable($m);
3397f9df 1531 } elsif ($m->{chg} eq 'M') {
cf52b8f0 1532 apply_mod_line_blob($m);
3397f9df
EW
1533 svn_check_prop_executable($m);
1534 } elsif ($m->{chg} eq 'T') {
cf52b8f0 1535 svn_check_prop_executable($m);
9ffd652a
EW
1536 apply_mod_line_blob($m);
1537 if ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1538 sys(qw(svn propdel svn:special), $m->{file_b});
1539 } else {
1540 sys(qw(svn propset svn:special *),$m->{file_b});
1541 }
3397f9df
EW
1542 } elsif ($m->{chg} eq 'A') {
1543 svn_ensure_parent_path( $m->{file_b} );
cf52b8f0 1544 apply_mod_line_blob($m);
0e8a002c 1545 sys(qw(svn add), $m->{file_b});
cf52b8f0 1546 svn_check_prop_executable($m);
3397f9df
EW
1547 } else {
1548 croak "Invalid chg: $m->{chg}\n";
1549 }
1550 }
cf52b8f0
EW
1551
1552 assert_tree($treeish);
1553 if ($_rmdir) { # remove empty directories
1554 handle_rmdir($rm, $add);
1555 }
1556 assert_tree($treeish);
1557 return $mods;
1558}
1559
a5e0cedc 1560sub libsvn_checkout_tree {
42d32870
EW
1561 my ($from, $treeish, $ed) = @_;
1562 my $mods = get_diff($from, $treeish);
a5e0cedc
EW
1563 return $mods unless (scalar @$mods);
1564 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1565 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1566 my $f = $m->{chg};
1567 if (defined $o{$f}) {
80f50749 1568 $ed->$f($m, $_q);
a5e0cedc
EW
1569 } else {
1570 croak "Invalid change type: $f\n";
1571 }
1572 }
80f50749 1573 $ed->rmdirs($_q) if $_rmdir;
a5e0cedc
EW
1574 return $mods;
1575}
1576
cf52b8f0
EW
1577# svn ls doesn't work with respect to the current working tree, but what's
1578# in the repository. There's not even an option for it... *sigh*
1579# (added files don't show up and removed files remain in the ls listing)
1580sub svn_ls_current {
1581 my ($dir, $rm, $add) = @_;
1582 chomp(my @ls = safe_qx('svn','ls',$dir));
1583 my @ret = ();
1584 foreach (@ls) {
1585 s#/$##; # trailing slashes are evil
1586 push @ret, $_ unless $rm->{$dir}->{$_};
1587 }
1588 if (exists $add->{$dir}) {
1589 push @ret, keys %{$add->{$dir}};
1590 }
1591 return \@ret;
1592}
1593
1594sub handle_rmdir {
1595 my ($rm, $add) = @_;
1596
1597 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1598 my $ls = svn_ls_current($dir, $rm, $add);
1599 next if (scalar @$ls);
1600 sys(qw(svn rm --force),$dir);
1601
1602 my $dn = dirname $dir;
1603 $rm->{ $dn }->{ basename $dir } = 1;
1604 $ls = svn_ls_current($dn, $rm, $add);
1605 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1606 sys(qw(svn rm --force),$dn);
1607 $dir = basename $dn;
1608 $dn = dirname $dn;
1609 $rm->{ $dn }->{ $dir } = 1;
1610 $ls = svn_ls_current($dn, $rm, $add);
3397f9df
EW
1611 }
1612 }
1613}
1614
a5e0cedc
EW
1615sub get_commit_message {
1616 my ($commit, $commit_msg) = (@_);
e17512f3 1617 my %log_msg = ( msg => '' );
ac8e0b91 1618 open my $msg, '>', $commit_msg or croak $!;
3397f9df
EW
1619
1620 chomp(my $type = `git-cat-file -t $commit`);
4ad4515d 1621 if ($type eq 'commit' || $type eq 'tag') {
3397f9df
EW
1622 my $pid = open my $msg_fh, '-|';
1623 defined $pid or croak $!;
1624
1625 if ($pid == 0) {
4ad4515d 1626 exec('git-cat-file', $type, $commit) or croak $!;
3397f9df
EW
1627 }
1628 my $in_msg = 0;
1629 while (<$msg_fh>) {
1630 if (!$in_msg) {
1631 $in_msg = 1 if (/^\s*$/);
df746c5a
EW
1632 } elsif (/^git-svn-id: /) {
1633 # skip this, we regenerate the correct one
1634 # on re-fetch anyways
3397f9df
EW
1635 } else {
1636 print $msg $_ or croak $!;
1637 }
1638 }
cf7424b0 1639 close $msg_fh or croak $?;
3397f9df
EW
1640 }
1641 close $msg or croak $!;
1642
1643 if ($_edit || ($type eq 'tree')) {
1644 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1645 system($editor, $commit_msg);
1646 }
ac8e0b91
EW
1647
1648 # file_to_s removes all trailing newlines, so just use chomp() here:
1649 open $msg, '<', $commit_msg or croak $!;
1650 { local $/; chomp($log_msg{msg} = <$msg>); }
1651 close $msg or croak $!;
1652
a5e0cedc
EW
1653 return \%log_msg;
1654}
1655
27e9fb8d
EW
1656sub set_svn_commit_env {
1657 if (defined $LC_ALL) {
1658 $ENV{LC_ALL} = $LC_ALL;
1659 } else {
1660 delete $ENV{LC_ALL};
1661 }
1662}
1663
a5e0cedc 1664sub svn_commit_tree {
42d32870 1665 my ($last, $commit) = @_;
a5e0cedc
EW
1666 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1667 my $log_msg = get_commit_message($commit, $commit_msg);
1668 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
ac8e0b91
EW
1669 print "Committing $commit: $oneline\n";
1670
27e9fb8d 1671 set_svn_commit_env();
3397f9df 1672 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
ce475dfc 1673 $ENV{LC_ALL} = 'C';
3397f9df 1674 unlink $commit_msg;
ce475dfc
EW
1675 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1676 if (!defined $committed) {
1677 my $out = join("\n",@ci_output);
1678 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1679 $out, "\n\nAssuming English locale...";
1680 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1681 defined $committed or die " FAILED!\n",
3397f9df 1682 "Commit output failed to parse committed revision!\n",
ce475dfc
EW
1683 print STDERR " OK\n";
1684 }
3397f9df 1685
e17512f3 1686 my @svn_up = qw(svn up);
3397f9df 1687 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
42d32870 1688 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
ce475dfc 1689 push @svn_up, "-r$committed";
e17512f3
EW
1690 sys(@svn_up);
1691 my $info = svn_info('.');
1692 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
ce475dfc
EW
1693 if ($info->{'Last Changed Rev'} != $committed) {
1694 croak "$info->{'Last Changed Rev'} != $committed\n"
e17512f3
EW
1695 }
1696 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1697 /(\d{4})\-(\d\d)\-(\d\d)\s
1698 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1699 or croak "Failed to parse date: $date\n";
a5e0cedc
EW
1700 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1701 $log_msg->{author} = $info->{'Last Changed Author'};
1702 $log_msg->{revision} = $committed;
1703 $log_msg->{msg} .= "\n";
42d32870
EW
1704 $log_msg->{parents} = [ $last->{commit} ];
1705 $log_msg->{commit} = git_commit($log_msg, $commit);
1706 return $log_msg;
e17512f3
EW
1707 }
1708 # resync immediately
42d32870 1709 push @svn_up, "-r$last->{revision}";
3397f9df 1710 sys(@svn_up);
42d32870 1711 return fetch("$committed=$commit");
3397f9df
EW
1712}
1713
9d55b41a
EW
1714sub rev_list_raw {
1715 my (@args) = @_;
1716 my $pid = open my $fh, '-|';
1717 defined $pid or croak $!;
1718 if (!$pid) {
1719 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1720 }
1721 return { fh => $fh, t => { } };
1722}
1723
1724sub next_rev_list_entry {
1725 my $rl = shift;
1726 my $fh = $rl->{fh};
1727 my $x = $rl->{t};
1728 while (<$fh>) {
1729 if (/^commit ($sha1)$/o) {
1730 if ($x->{c}) {
1731 $rl->{t} = { c => $1 };
1732 return $x;
1733 } else {
1734 $x->{c} = $1;
1735 }
1736 } elsif (/^parent ($sha1)$/o) {
1737 $x->{p}->{$1} = 1;
1738 } elsif (s/^ //) {
1739 $x->{m} ||= '';
1740 $x->{m} .= $_;
1741 }
1742 }
1743 return ($x != $rl->{t}) ? $x : undef;
1744}
1745
03823184
EW
1746# read the entire log into a temporary file (which is removed ASAP)
1747# and store the file handle + parser state
3397f9df
EW
1748sub svn_log_raw {
1749 my (@log_args) = @_;
03823184
EW
1750 my $log_fh = IO::File->new_tmpfile or croak $!;
1751 my $pid = fork;
3397f9df 1752 defined $pid or croak $!;
03823184
EW
1753 if (!$pid) {
1754 open STDOUT, '>&', $log_fh or croak $!;
3397f9df
EW
1755 exec (qw(svn log), @log_args) or croak $!
1756 }
03823184 1757 waitpid $pid, 0;
b8c92cad 1758 croak $? if $?;
03823184
EW
1759 seek $log_fh, 0, 0 or croak $!;
1760 return { state => 'sep', fh => $log_fh };
1761}
1762
1763sub next_log_entry {
1764 my $log = shift; # retval of svn_log_raw()
1765 my $ret = undef;
1766 my $fh = $log->{fh};
3397f9df 1767
03823184 1768 while (<$fh>) {
3397f9df
EW
1769 chomp;
1770 if (/^\-{72}$/) {
03823184
EW
1771 if ($log->{state} eq 'msg') {
1772 if ($ret->{lines}) {
1773 $ret->{msg} .= $_."\n";
1774 unless(--$ret->{lines}) {
1775 $log->{state} = 'sep';
ce6f3519
EW
1776 }
1777 } else {
1778 croak "Log parse error at: $_\n",
03823184 1779 $ret->{revision},
ce6f3519
EW
1780 "\n";
1781 }
1782 next;
1783 }
03823184 1784 if ($log->{state} ne 'sep') {
ce6f3519 1785 croak "Log parse error at: $_\n",
03823184
EW
1786 "state: $log->{state}\n",
1787 $ret->{revision},
ce6f3519
EW
1788 "\n";
1789 }
03823184 1790 $log->{state} = 'rev';
3397f9df
EW
1791
1792 # if we have an empty log message, put something there:
03823184
EW
1793 if ($ret) {
1794 $ret->{msg} ||= "\n";
1795 delete $ret->{lines};
1796 return $ret;
3397f9df
EW
1797 }
1798 next;
1799 }
03823184 1800 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
3397f9df 1801 my $rev = $1;
ce6f3519
EW
1802 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1803 ($lines) = ($lines =~ /(\d+)/);
f7bae37f
SP
1804 $date = '1970-01-01 00:00:00 +0000'
1805 if ($_ignore_nodate && $date eq '(no date)');
3397f9df
EW
1806 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1807 /(\d{4})\-(\d\d)\-(\d\d)\s
1808 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1809 or croak "Failed to parse date: $date\n";
03823184 1810 $ret = { revision => $rev,
3397f9df
EW
1811 date => "$tz $Y-$m-$d $H:$M:$S",
1812 author => $author,
ce6f3519 1813 lines => $lines,
03823184 1814 msg => '' };
a9612be2
EW
1815 if (defined $_authors && ! defined $users{$author}) {
1816 die "Author: $author not defined in ",
1817 "$_authors file\n";
1818 }
03823184 1819 $log->{state} = 'msg_start';
3397f9df
EW
1820 next;
1821 }
1822 # skip the first blank line of the message:
03823184
EW
1823 if ($log->{state} eq 'msg_start' && /^$/) {
1824 $log->{state} = 'msg';
1825 } elsif ($log->{state} eq 'msg') {
1826 if ($ret->{lines}) {
1827 $ret->{msg} .= $_."\n";
1828 unless (--$ret->{lines}) {
1829 $log->{state} = 'sep';
ce6f3519
EW
1830 }
1831 } else {
1832 croak "Log parse error at: $_\n",
03823184 1833 $ret->{revision},"\n";
ce6f3519 1834 }
3397f9df
EW
1835 }
1836 }
03823184 1837 return $ret;
3397f9df
EW
1838}
1839
1840sub svn_info {
1841 my $url = shift || $SVN_URL;
1842
1843 my $pid = open my $info_fh, '-|';
1844 defined $pid or croak $!;
1845
1846 if ($pid == 0) {
1847 exec(qw(svn info),$url) or croak $!;
1848 }
1849
1850 my $ret = {};
1851 # only single-lines seem to exist in svn info output
1852 while (<$info_fh>) {
1853 chomp $_;
e17512f3 1854 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
3397f9df
EW
1855 $ret->{$1} = $2;
1856 push @{$ret->{-order}}, $1;
1857 }
1858 }
cf7424b0 1859 close $info_fh or croak $?;
3397f9df
EW
1860 return $ret;
1861}
1862
1863sub sys { system(@_) == 0 or croak $? }
1864
36f5b1f0
EW
1865sub do_update_index {
1866 my ($z_cmd, $cmd, $no_text_base) = @_;
1867
1868 my $z = open my $p, '-|';
1869 defined $z or croak $!;
1870 unless ($z) { exec @$z_cmd or croak $! }
1871
1872 my $pid = open my $ui, '|-';
1873 defined $pid or croak $!;
1874 unless ($pid) {
1875 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1876 }
1877 local $/ = "\0";
1878 while (my $x = <$p>) {
1879 chomp $x;
1880 if (!$no_text_base && lstat $x && ! -l _ &&
8a97e368 1881 svn_propget_base('svn:keywords', $x)) {
36f5b1f0
EW
1882 my $mode = -x _ ? 0755 : 0644;
1883 my ($v,$d,$f) = File::Spec->splitpath($x);
1884 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1885 'text-base',"$f.svn-base");
1886 $tb =~ s#^/##;
1887 unless (-f $tb) {
1888 $tb = File::Spec->catfile($d, '.svn',
1889 'text-base',"$f.svn-base");
1890 $tb =~ s#^/##;
1891 }
17a10f37 1892 my @s = stat($x);
36f5b1f0 1893 unlink $x or croak $!;
17a10f37 1894 copy($tb, $x);
36f5b1f0 1895 chmod(($mode &~ umask), $x) or croak $!;
17a10f37 1896 utime $s[8], $s[9], $x;
36f5b1f0
EW
1897 }
1898 print $ui $x,"\0";
1899 }
cf7424b0 1900 close $ui or croak $?;
36f5b1f0
EW
1901}
1902
1903sub index_changes {
a5e0cedc 1904 return if $_use_lib;
6c5cda89
EW
1905
1906 if (!-f "$GIT_SVN_DIR/info/exclude") {
1907 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1908 print $fd '.svn',"\n";
1909 close $fd or croak $!;
1910 }
36f5b1f0
EW
1911 my $no_text_base = shift;
1912 do_update_index([qw/git-diff-files --name-only -z/],
1913 'remove',
1914 $no_text_base);
1915 do_update_index([qw/git-ls-files -z --others/,
883d0a78 1916 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
36f5b1f0
EW
1917 'add',
1918 $no_text_base);
3397f9df
EW
1919}
1920
1921sub s_to_file {
1922 my ($str, $file, $mode) = @_;
1923 open my $fd,'>',$file or croak $!;
1924 print $fd $str,"\n" or croak $!;
1925 close $fd or croak $!;
1926 chmod ($mode &~ umask, $file) if (defined $mode);
1927}
1928
1929sub file_to_s {
1930 my $file = shift;
1931 open my $fd,'<',$file or croak "$!: file: $file\n";
1932 local $/;
1933 my $ret = <$fd>;
1934 close $fd or croak $!;
1935 $ret =~ s/\s*$//s;
1936 return $ret;
1937}
1938
1939sub assert_revision_unknown {
42d32870
EW
1940 my $r = shift;
1941 if (my $c = revdb_get($REVDB, $r)) {
1942 croak "$r = $c already exists! Why are we refetching it?";
3397f9df
EW
1943 }
1944}
1945
ac749050
EW
1946sub trees_eq {
1947 my ($x, $y) = @_;
1948 my @x = safe_qx('git-cat-file','commit',$x);
1949 my @y = safe_qx('git-cat-file','commit',$y);
1950 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1951 || $y[0] !~ /^tree $sha1\n$/) {
1952 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1953 return 0
1954 }
1955 return 1;
1956}
1957
3397f9df
EW
1958sub git_commit {
1959 my ($log_msg, @parents) = @_;
1960 assert_revision_unknown($log_msg->{revision});
69f0d91e
EW
1961 map_tree_joins() if (@_branch_from && !%tree_map);
1962
a5e0cedc
EW
1963 my (@tmp_parents, @exec_parents, %seen_parent);
1964 if (my $lparents = $log_msg->{parents}) {
1965 @tmp_parents = @$lparents
1966 }
3397f9df
EW
1967 # commit parents can be conditionally bound to a particular
1968 # svn revision via: "svn_revno=commit_sha1", filter them out here:
3397f9df
EW
1969 foreach my $p (@parents) {
1970 next unless defined $p;
1971 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1972 if ($1 == $log_msg->{revision}) {
a5e0cedc 1973 push @tmp_parents, $2;
3397f9df
EW
1974 }
1975 } else {
a5e0cedc 1976 push @tmp_parents, $p if $p =~ /$sha1_short/o;
3397f9df
EW
1977 }
1978 }
a5e0cedc
EW
1979 my $tree = $log_msg->{tree};
1980 if (!defined $tree) {
1981 my $index = set_index($GIT_SVN_INDEX);
36f5b1f0 1982 index_changes();
a5e0cedc 1983 chomp($tree = `git-write-tree`);
b8c92cad 1984 croak $? if $?;
a5e0cedc
EW
1985 restore_index($index);
1986 }
a00439ac
EW
1987
1988 # just in case we clobber the existing ref, we still want that ref
1989 # as our parent:
1990 if (my $cur = eval { file_to_s("$GIT_DIR/refs/remotes/$GIT_SVN") }) {
1991 push @tmp_parents, $cur;
1992 }
1993
a5e0cedc 1994 if (exists $tree_map{$tree}) {
c1927a85
EW
1995 foreach my $p (@{$tree_map{$tree}}) {
1996 my $skip;
1997 foreach (@tmp_parents) {
1998 # see if a common parent is found
1999 my $mb = eval {
2000 safe_qx('git-merge-base', $_, $p)
2001 };
2002 next if ($@ || $?);
2003 $skip = 1;
2004 last;
2005 }
2006 next if $skip;
2007 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
2008 next if (($SVN_UUID eq $uuid_p) &&
2009 ($log_msg->{revision} > $r_p));
2010 next if (defined $url_p && defined $SVN_URL &&
2011 ($SVN_UUID eq $uuid_p) &&
2012 ($url_p eq $SVN_URL));
2013 push @tmp_parents, $p;
2014 }
a5e0cedc
EW
2015 }
2016 foreach (@tmp_parents) {
2017 next if $seen_parent{$_};
2018 $seen_parent{$_} = 1;
2019 push @exec_parents, $_;
2020 # MAXPARENT is defined to 16 in commit-tree.c:
2021 last if @exec_parents > 16;
2022 }
2023
a00439ac
EW
2024 set_commit_env($log_msg);
2025 my @exec = ('git-commit-tree', $tree);
2026 push @exec, '-p', $_ foreach @exec_parents;
2027 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2028 or croak $!;
2029 print $msg_fh $log_msg->{msg} or croak $!;
2030 unless ($_no_metadata) {
2031 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision}",
1ca72aef 2032 " $SVN_UUID\n" or croak $!;
3397f9df 2033 }
a00439ac
EW
2034 $msg_fh->flush == 0 or croak $!;
2035 close $msg_fh or croak $!;
3397f9df 2036 chomp(my $commit = do { local $/; <$out_fh> });
a00439ac
EW
2037 close $out_fh or croak $!;
2038 waitpid $pid, 0;
2039 croak $? if $?;
3397f9df 2040 if ($commit !~ /^$sha1$/o) {
a00439ac 2041 die "Failed to commit, invalid sha1: $commit\n";
3397f9df 2042 }
a00439ac 2043 sys('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
42d32870
EW
2044 revdb_set($REVDB, $log_msg->{revision}, $commit);
2045
a5e0cedc 2046 # this output is read via pipe, do not change:
3397f9df 2047 print "r$log_msg->{revision} = $commit\n";
cf7424b0
EW
2048 check_repack();
2049 return $commit;
2050}
2051
2052sub check_repack {
dc5869c0
EW
2053 if ($_repack && (--$_repack_nr == 0)) {
2054 $_repack_nr = $_repack;
2055 sys("git repack $_repack_flags");
2056 }
3397f9df
EW
2057}
2058
a9612be2 2059sub set_commit_env {
1ca72aef 2060 my ($log_msg) = @_;
a9612be2 2061 my $author = $log_msg->{author};
a5e0cedc
EW
2062 if (!defined $author || length $author == 0) {
2063 $author = '(no author)';
2064 }
a9612be2 2065 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1ca72aef 2066 : ($author,"$author\@$SVN_UUID");
a9612be2
EW
2067 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2068 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2069 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2070}
2071
cf52b8f0
EW
2072sub apply_mod_line_blob {
2073 my $m = shift;
2074 if ($m->{mode_b} =~ /^120/) {
2075 blob_to_symlink($m->{sha1_b}, $m->{file_b});
2076 } else {
2077 blob_to_file($m->{sha1_b}, $m->{file_b});
2078 }
2079}
2080
3397f9df
EW
2081sub blob_to_symlink {
2082 my ($blob, $link) = @_;
2083 defined $link or croak "\$link not defined!\n";
2084 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
2085 if (-l $link || -f _) {
2086 unlink $link or croak $!;
2087 }
2088
3397f9df
EW
2089 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
2090 symlink $dest, $link or croak $!;
2091}
2092
2093sub blob_to_file {
2094 my ($blob, $file) = @_;
2095 defined $file or croak "\$file not defined!\n";
2096 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
cf52b8f0
EW
2097 if (-l $file || -f _) {
2098 unlink $file or croak $!;
2099 }
2100
3397f9df
EW
2101 open my $blob_fh, '>', $file or croak "$!: $file\n";
2102 my $pid = fork;
2103 defined $pid or croak $!;
2104
2105 if ($pid == 0) {
2106 open STDOUT, '>&', $blob_fh or croak $!;
b8c92cad 2107 exec('git-cat-file','blob',$blob) or croak $!;
3397f9df
EW
2108 }
2109 waitpid $pid, 0;
2110 croak $? if $?;
2111
2112 close $blob_fh or croak $!;
2113}
2114
2115sub safe_qx {
2116 my $pid = open my $child, '-|';
2117 defined $pid or croak $!;
2118 if ($pid == 0) {
b8c92cad 2119 exec(@_) or croak $!;
3397f9df
EW
2120 }
2121 my @ret = (<$child>);
2122 close $child or croak $?;
2123 die $? if $?; # just in case close didn't error out
2124 return wantarray ? @ret : join('',@ret);
2125}
2126
1d52aba8 2127sub svn_compat_check {
a00439ac
EW
2128 if ($_follow_parent) {
2129 print STDERR 'E: --follow-parent functionality is only ',
2130 "available when SVN libraries are used\n";
2131 exit 1;
2132 }
1d52aba8
EW
2133 my @co_help = safe_qx(qw(svn co -h));
2134 unless (grep /ignore-externals/,@co_help) {
3397f9df
EW
2135 print STDERR "W: Installed svn version does not support ",
2136 "--ignore-externals\n";
2137 $_no_ignore_ext = 1;
2138 }
1d52aba8
EW
2139 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2140 $_svn_co_url_revs = 1;
2141 }
8a97e368
EW
2142 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2143 $_svn_pg_peg_revs = 1;
2144 }
7317ed90
EW
2145
2146 # I really, really hope nobody hits this...
2147 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2148 print STDERR <<'';
2149W: The installed svn version does not support the --stop-on-copy flag in
2150 the log command.
2151 Lets hope the directory you're tracking is not a branch or tag
2152 and was never moved within the repository...
2153
2154 $_no_stop_copy = 1;
2155 }
1d52aba8
EW
2156}
2157
2158# *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2159# (and they won't honor URL@<rev> without -r<rev>, too!)
2160sub svn_cmd_checkout {
2161 my ($url, $rev, $dir) = @_;
2162 my @cmd = ('svn','co', "-r$rev");
2163 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2164 $url .= "\@$rev" if $_svn_co_url_revs;
2165 sys(@cmd, $url, $dir);
3397f9df 2166}
2beb3cdd
EW
2167
2168sub check_upgrade_needed {
cf7424b0 2169 if (!-r $REVDB) {
1a82e793 2170 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
cf7424b0
EW
2171 open my $fh, '>>',$REVDB or croak $!;
2172 close $fh;
2173 }
2beb3cdd
EW
2174 my $old = eval {
2175 my $pid = open my $child, '-|';
2176 defined $pid or croak $!;
2177 if ($pid == 0) {
2178 close STDERR;
b8c92cad 2179 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2beb3cdd
EW
2180 }
2181 my @ret = (<$child>);
2182 close $child or croak $?;
2183 die $? if $?; # just in case close didn't error out
2184 return wantarray ? @ret : join('',@ret);
2185 };
2186 return unless $old;
2187 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
2188 if ($@ || !$head) {
2189 print STDERR "Please run: $0 rebuild --upgrade\n";
2190 exit 1;
2191 }
2192}
2193
69f0d91e
EW
2194# fills %tree_map with a reverse mapping of trees to commits. Useful
2195# for finding parents to commit on.
2196sub map_tree_joins {
098749d9 2197 my %seen;
69f0d91e
EW
2198 foreach my $br (@_branch_from) {
2199 my $pid = open my $pipe, '-|';
2200 defined $pid or croak $!;
2201 if ($pid == 0) {
098749d9 2202 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
b8c92cad 2203 or croak $!;
69f0d91e
EW
2204 }
2205 while (<$pipe>) {
2206 if (/^commit ($sha1)$/o) {
2207 my $commit = $1;
098749d9
EW
2208
2209 # if we've seen a commit,
2210 # we've seen its parents
2211 last if $seen{$commit};
69f0d91e
EW
2212 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2213 unless (defined $tree) {
2214 die "Failed to parse commit $commit\n";
2215 }
2216 push @{$tree_map{$tree}}, $commit;
098749d9 2217 $seen{$commit} = 1;
69f0d91e
EW
2218 }
2219 }
098749d9 2220 close $pipe; # we could be breaking the pipe early
69f0d91e
EW
2221 }
2222}
2223
bf78b1d8
EW
2224sub load_all_refs {
2225 if (@_branch_from) {
2226 print STDERR '--branch|-b parameters are ignored when ',
2227 "--branch-all-refs|-B is passed\n";
2228 }
2229
2230 # don't worry about rev-list on non-commit objects/tags,
2231 # it shouldn't blow up if a ref is a blob or tree...
2232 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2233}
2234
eeb0abe0
EW
2235# '<svn username> = real-name <email address>' mapping based on git-svnimport:
2236sub load_authors {
2237 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2238 while (<$authors>) {
2239 chomp;
8815788e 2240 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0
EW
2241 my ($user, $name, $email) = ($1, $2, $3);
2242 $users{$user} = [$name, $email];
2243 }
2244 close $authors or croak $!;
2245}
2246
79bb8d88
EW
2247sub rload_authors {
2248 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2249 while (<$authors>) {
2250 chomp;
2251 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2252 my ($user, $name, $email) = ($1, $2, $3);
2253 $rusers{"$name <$email>"} = $user;
2254 }
2255 close $authors or croak $!;
2256}
2257
8a97e368
EW
2258sub svn_propget_base {
2259 my ($p, $f) = @_;
2260 $f .= '@BASE' if $_svn_pg_peg_revs;
2261 return safe_qx(qw/svn propget/, $p, $f);
2262}
2263
9d55b41a
EW
2264sub git_svn_each {
2265 my $sub = shift;
2266 foreach (`git-rev-parse --symbolic --all`) {
2267 next unless s#^refs/remotes/##;
2268 chomp $_;
2269 next unless -f "$GIT_DIR/svn/$_/info/url";
2270 &$sub($_);
2271 }
2272}
2273
42d32870
EW
2274sub migrate_revdb {
2275 git_svn_each(sub {
2276 my $id = shift;
2277 defined(my $pid = fork) or croak $!;
2278 if (!$pid) {
2279 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2280 init_vars();
2281 exit 0 if -r $REVDB;
2282 print "Upgrading svn => git mapping...\n";
1a82e793 2283 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
42d32870
EW
2284 open my $fh, '>>',$REVDB or croak $!;
2285 close $fh;
2286 rebuild();
2287 print "Done upgrading. You may now delete the ",
2288 "deprecated $GIT_SVN_DIR/revs directory\n";
2289 exit 0;
2290 }
2291 waitpid $pid, 0;
2292 croak $? if $?;
2293 });
2294}
2295
883d0a78 2296sub migration_check {
42d32870 2297 migrate_revdb() unless (-e $REVDB);
883d0a78
EW
2298 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2299 print "Upgrading repository...\n";
2300 unless (-d "$GIT_DIR/svn") {
2301 mkdir "$GIT_DIR/svn" or croak $!;
2302 }
2303 print "Data from a previous version of git-svn exists, but\n\t",
2304 "$GIT_SVN_DIR\n\t(required for this version ",
2305 "($VERSION) of git-svn) does not.\n";
2306
2307 foreach my $x (`git-rev-parse --symbolic --all`) {
2308 next unless $x =~ s#^refs/remotes/##;
2309 chomp $x;
2310 next unless -f "$GIT_DIR/$x/info/url";
2311 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2312 next unless $u;
2313 my $dn = dirname("$GIT_DIR/svn/$x");
2314 mkpath([$dn]) unless -d $dn;
2315 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
883d0a78 2316 }
42d32870 2317 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
883d0a78
EW
2318 print "Done upgrading.\n";
2319}
2320
9d55b41a 2321sub find_rev_before {
42d32870
EW
2322 my ($r, $id, $eq_ok) = @_;
2323 my $f = "$GIT_DIR/svn/$id/.rev_db";
cf7424b0
EW
2324 return (undef,undef) unless -r $f;
2325 --$r unless $eq_ok;
42d32870
EW
2326 while ($r > 0) {
2327 if (my $c = revdb_get($f, $r)) {
2328 return ($r, $c);
2329 }
2330 --$r;
9d55b41a
EW
2331 }
2332 return (undef, undef);
2333}
2334
b8c92cad
EW
2335sub init_vars {
2336 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2337 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
42d32870 2338 $REVDB = "$GIT_SVN_DIR/.rev_db";
b8c92cad
EW
2339 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2340 $SVN_URL = undef;
b8c92cad 2341 $SVN_WC = "$GIT_SVN_DIR/tree";
c1927a85 2342 %tree_map = ();
b8c92cad
EW
2343}
2344
2345# convert GetOpt::Long specs for use by git-repo-config
2346sub read_repo_config {
2347 return unless -d $GIT_DIR;
2348 my $opts = shift;
2349 foreach my $o (keys %$opts) {
2350 my $v = $opts->{$o};
2351 my ($key) = ($o =~ /^([a-z\-]+)/);
2352 $key =~ s/-//g;
2353 my $arg = 'git-repo-config';
2354 $arg .= ' --int' if ($o =~ /[:=]i$/);
2355 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2356 if (ref $v eq 'ARRAY') {
2357 chomp(my @tmp = `$arg --get-all svn.$key`);
2358 @$v = @tmp if @tmp;
2359 } else {
2360 chomp(my $tmp = `$arg --get svn.$key`);
2361 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2362 $$v = $tmp;
2363 }
2364 }
2365 }
2366}
2367
dc5869c0
EW
2368sub set_default_vals {
2369 if (defined $_repack) {
2370 $_repack = 1000 if ($_repack <= 0);
2371 $_repack_nr = $_repack;
cf7424b0 2372 $_repack_flags ||= '-d';
dc5869c0
EW
2373 }
2374}
2375
9d55b41a
EW
2376sub read_grafts {
2377 my $gr_file = shift;
2378 my ($grafts, $comments) = ({}, {});
2379 if (open my $fh, '<', $gr_file) {
2380 my @tmp;
2381 while (<$fh>) {
2382 if (/^($sha1)\s+/) {
2383 my $c = $1;
2384 if (@tmp) {
2385 @{$comments->{$c}} = @tmp;
2386 @tmp = ();
2387 }
2388 foreach my $p (split /\s+/, $_) {
2389 $grafts->{$c}->{$p} = 1;
2390 }
2391 } else {
2392 push @tmp, $_;
2393 }
2394 }
2395 close $fh or croak $!;
2396 @{$comments->{'END'}} = @tmp if @tmp;
2397 }
2398 return ($grafts, $comments);
2399}
2400
2401sub write_grafts {
2402 my ($grafts, $comments, $gr_file) = @_;
2403
2404 open my $fh, '>', $gr_file or croak $!;
2405 foreach my $c (sort keys %$grafts) {
2406 if ($comments->{$c}) {
2407 print $fh $_ foreach @{$comments->{$c}};
2408 }
2409 my $p = $grafts->{$c};
c1927a85 2410 my %x; # real parents
9d55b41a
EW
2411 delete $p->{$c}; # commits are not self-reproducing...
2412 my $pid = open my $ch, '-|';
2413 defined $pid or croak $!;
2414 if (!$pid) {
2415 exec(qw/git-cat-file commit/, $c) or croak $!;
2416 }
2417 while (<$ch>) {
c1927a85
EW
2418 if (/^parent ($sha1)/) {
2419 $x{$1} = $p->{$1} = 1;
9d55b41a 2420 } else {
c1927a85 2421 last unless /^\S/;
9d55b41a
EW
2422 }
2423 }
2424 close $ch; # breaking the pipe
c1927a85
EW
2425
2426 # if real parents are the only ones in the grafts, drop it
2427 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2428
2429 my (@ip, @jp, $mb);
2430 my %del = %x;
2431 @ip = @jp = keys %$p;
2432 foreach my $i (@ip) {
2433 next if $del{$i} || $p->{$i} == 2;
2434 foreach my $j (@jp) {
2435 next if $i eq $j || $del{$j} || $p->{$j} == 2;
2436 $mb = eval { safe_qx('git-merge-base',$i,$j) };
2437 next unless $mb;
2438 chomp $mb;
2439 next if $x{$mb};
2440 if ($mb eq $j) {
2441 delete $p->{$i};
2442 $del{$i} = 1;
2443 } elsif ($mb eq $i) {
2444 delete $p->{$j};
2445 $del{$j} = 1;
2446 }
2447 }
2448 }
2449
2450 # if real parents are the only ones in the grafts, drop it
2451 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2452
9d55b41a
EW
2453 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2454 }
2455 if ($comments->{'END'}) {
2456 print $fh $_ foreach @{$comments->{'END'}};
2457 }
2458 close $fh or croak $!;
2459}
2460
a00439ac
EW
2461sub read_url_paths_all {
2462 my ($l_map, $pfx, $p) = @_;
2463 my @dir;
2464 foreach (<$p/*>) {
2465 if (-r "$_/info/url") {
2466 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2467 my $id = $pfx . basename $_;
2468 my $url = file_to_s("$_/info/url");
2469 my ($u, $p) = repo_path_split($url);
2470 $l_map->{$u}->{$p} = $id;
2471 } elsif (-d $_) {
2472 push @dir, $_;
2473 }
2474 }
2475 foreach (@dir) {
2476 my $x = $_;
2477 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
2478 read_url_paths_all($l_map, $x, $_);
2479 }
2480}
2481
2482# this one only gets ids that have been imported, not new ones
9d55b41a
EW
2483sub read_url_paths {
2484 my $l_map = {};
2485 git_svn_each(sub { my $x = shift;
6c5cda89
EW
2486 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2487 my ($u, $p) = repo_path_split($url);
9d55b41a
EW
2488 $l_map->{$u}->{$p} = $x;
2489 });
2490 return $l_map;
2491}
2492
79bb8d88 2493sub extract_metadata {
c1927a85 2494 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
2495 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2496 \s([a-f\d\-]+)$/x);
e70dc780 2497 if (!defined $rev || !$uuid || !$url) {
79bb8d88 2498 # some of the original repositories I made had
82e5a82f 2499 # identifiers like this:
79bb8d88
EW
2500 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2501 }
2502 return ($url, $rev, $uuid);
2503}
2504
c1927a85
EW
2505sub cmt_metadata {
2506 return extract_metadata((grep(/^git-svn-id: /,
2507 safe_qx(qw/git-cat-file commit/, shift)))[-1]);
2508}
2509
2510sub get_commit_time {
2511 my $cmt = shift;
2512 defined(my $pid = open my $fh, '-|') or croak $!;
2513 if (!$pid) {
2514 exec qw/git-rev-list --pretty=raw -n1/, $cmt or croak $!;
2515 }
2516 while (<$fh>) {
2517 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2518 my ($s, $tz) = ($1, $2);
2519 if ($tz =~ s/^\+//) {
2520 $s += tz_to_s_offset($tz);
2521 } elsif ($tz =~ s/^\-//) {
2522 $s -= tz_to_s_offset($tz);
2523 }
2524 close $fh;
2525 return $s;
2526 }
2527 die "Can't get commit time for commit: $cmt\n";
2528}
2529
79bb8d88
EW
2530sub tz_to_s_offset {
2531 my ($tz) = @_;
2532 $tz =~ s/(\d\d)$//;
2533 return ($1 * 60) + ($tz * 3600);
2534}
2535
2536sub setup_pager { # translated to Perl from pager.c
2537 return unless (-t *STDOUT);
2538 my $pager = $ENV{PAGER};
2539 if (!defined $pager) {
2540 $pager = 'less';
2541 } elsif (length $pager == 0 || $pager eq 'cat') {
2542 return;
2543 }
2544 pipe my $rfd, my $wfd or return;
2545 defined(my $pid = fork) or croak $!;
2546 if (!$pid) {
2547 open STDOUT, '>&', $wfd or croak $!;
2548 return;
2549 }
2550 open STDIN, '<&', $rfd or croak $!;
2551 $ENV{LESS} ||= '-S';
2552 exec $pager or croak "Can't run pager: $!\n";;
2553}
2554
2555sub get_author_info {
2556 my ($dest, $author, $t, $tz) = @_;
2557 $author =~ s/(?:^\s*|\s*$)//g;
c0d48222 2558 $dest->{a_raw} = $author;
79bb8d88
EW
2559 my $_a;
2560 if ($_authors) {
2561 $_a = $rusers{$author} || undef;
2562 }
2563 if (!$_a) {
2564 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2565 }
2566 $dest->{t} = $t;
2567 $dest->{tz} = $tz;
2568 $dest->{a} = $_a;
2569 # Date::Parse isn't in the standard Perl distro :(
2570 if ($tz =~ s/^\+//) {
2571 $t += tz_to_s_offset($tz);
2572 } elsif ($tz =~ s/^\-//) {
2573 $t -= tz_to_s_offset($tz);
2574 }
2575 $dest->{t_utc} = $t;
2576}
2577
2578sub process_commit {
2579 my ($c, $r_min, $r_max, $defer) = @_;
2580 if (defined $r_min && defined $r_max) {
2581 if ($r_min == $c->{r} && $r_min == $r_max) {
2582 show_commit($c);
2583 return 0;
2584 }
2585 return 1 if $r_min == $r_max;
2586 if ($r_min < $r_max) {
2587 # we need to reverse the print order
2588 return 0 if (defined $_limit && --$_limit < 0);
2589 push @$defer, $c;
2590 return 1;
2591 }
2592 if ($r_min != $r_max) {
2593 return 1 if ($r_min < $c->{r});
2594 return 1 if ($r_max > $c->{r});
2595 }
2596 }
2597 return 0 if (defined $_limit && --$_limit < 0);
2598 show_commit($c);
2599 return 1;
2600}
2601
2602sub show_commit {
2603 my $c = shift;
2604 if ($_oneline) {
2605 my $x = "\n";
2606 if (my $l = $c->{l}) {
2607 while ($l->[0] =~ /^\s*$/) { shift @$l }
2608 $x = $l->[0];
2609 }
2610 $_l_fmt ||= 'A' . length($c->{r});
2611 print 'r',pack($_l_fmt, $c->{r}),' | ';
2612 print "$c->{c} | " if $_show_commit;
2613 print $x;
2614 } else {
2615 show_commit_normal($c);
2616 }
2617}
2618
74a31a10
EW
2619sub show_commit_changed_paths {
2620 my ($c) = @_;
2621 return unless $c->{changed};
2622 print "Changed paths:\n", @{$c->{changed}};
2623}
2624
79bb8d88
EW
2625sub show_commit_normal {
2626 my ($c) = @_;
2627 print '-' x72, "\nr$c->{r} | ";
2628 print "$c->{c} | " if $_show_commit;
2629 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2630 localtime($c->{t_utc})), ' | ';
2631 my $nr_line = 0;
2632
2633 if (my $l = $c->{l}) {
74a31a10
EW
2634 while ($l->[$#$l] eq "\n" && $#$l > 0
2635 && $l->[($#$l - 1)] eq "\n") {
79bb8d88
EW
2636 pop @$l;
2637 }
2638 $nr_line = scalar @$l;
2639 if (!$nr_line) {
2640 print "1 line\n\n\n";
2641 } else {
2642 if ($nr_line == 1) {
2643 $nr_line = '1 line';
2644 } else {
2645 $nr_line .= ' lines';
2646 }
74a31a10
EW
2647 print $nr_line, "\n";
2648 show_commit_changed_paths($c);
2649 print "\n";
79bb8d88
EW
2650 print $_ foreach @$l;
2651 }
2652 } else {
74a31a10
EW
2653 print "1 line\n";
2654 show_commit_changed_paths($c);
2655 print "\n";
79bb8d88
EW
2656
2657 }
2658 foreach my $x (qw/raw diff/) {
2659 if ($c->{$x}) {
2660 print "\n";
2661 print $_ foreach @{$c->{$x}}
2662 }
2663 }
2664}
2665
a5e0cedc
EW
2666sub libsvn_load {
2667 return unless $_use_lib;
2668 $_use_lib = eval {
2669 require SVN::Core;
dc62e25c
EW
2670 if ($SVN::Core::VERSION lt '1.1.0') {
2671 die "Need SVN::Core 1.1.0 or better ",
a5e0cedc
EW
2672 "(got $SVN::Core::VERSION) ",
2673 "Falling back to command-line svn\n";
2674 }
2675 require SVN::Ra;
2676 require SVN::Delta;
2677 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2678 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2679 $SVN::Node::dir.$SVN::Node::unknown.
2680 $SVN::Node::none.$SVN::Node::file.
30d055aa
EW
2681 $SVN::Node::dir.$SVN::Node::unknown.
2682 $SVN::Auth::SSL::CNMISMATCH.
2683 $SVN::Auth::SSL::NOTYETVALID.
2684 $SVN::Auth::SSL::EXPIRED.
2685 $SVN::Auth::SSL::UNKNOWNCA.
2686 $SVN::Auth::SSL::OTHER;
a5e0cedc
EW
2687 1;
2688 };
2689}
2690
30d055aa
EW
2691sub _simple_prompt {
2692 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2693 $may_save = undef if $_no_auth_cache;
2694 $default_username = $_username if defined $_username;
2695 if (defined $default_username && length $default_username) {
2696 if (defined $realm && length $realm) {
2697 print "Authentication realm: $realm\n";
2698 }
2699 $cred->username($default_username);
2700 } else {
2701 _username_prompt($cred, $realm, $may_save, $pool);
2702 }
2703 $cred->password(_read_password("Password for '" .
2704 $cred->username . "': ", $realm));
2705 $cred->may_save($may_save);
2706 $SVN::_Core::SVN_NO_ERROR;
2707}
2708
2709sub _ssl_server_trust_prompt {
2710 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2711 $may_save = undef if $_no_auth_cache;
2712 print "Error validating server certificate for '$realm':\n";
2713 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2714 print " - The certificate is not issued by a trusted ",
2715 "authority. Use the\n",
2716 " fingerprint to validate the certificate manually!\n";
2717 }
2718 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2719 print " - The certificate hostname does not match.\n";
2720 }
2721 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2722 print " - The certificate is not yet valid.\n";
2723 }
2724 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2725 print " - The certificate has expired.\n";
2726 }
2727 if ($failures & $SVN::Auth::SSL::OTHER) {
2728 print " - The certificate has an unknown error.\n";
2729 }
2730 printf( "Certificate information:\n".
2731 " - Hostname: %s\n".
2732 " - Valid: from %s until %s\n".
2733 " - Issuer: %s\n".
2734 " - Fingerprint: %s\n",
2735 map $cert_info->$_, qw(hostname valid_from valid_until
2736 issuer_dname fingerprint) );
2737 my $choice;
2738prompt:
2739 print $may_save ?
2740 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2741 "(R)eject or accept (t)emporarily? ";
2742 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2743 if ($choice =~ /^t$/i) {
2744 $cred->may_save(undef);
2745 } elsif ($choice =~ /^r$/i) {
2746 return -1;
2747 } elsif ($may_save && $choice =~ /^p$/i) {
2748 $cred->may_save($may_save);
2749 } else {
2750 goto prompt;
2751 }
2752 $cred->accepted_failures($failures);
2753 $SVN::_Core::SVN_NO_ERROR;
2754}
2755
2756sub _ssl_client_cert_prompt {
2757 my ($cred, $realm, $may_save, $pool) = @_;
2758 $may_save = undef if $_no_auth_cache;
2759 print "Client certificate filename: ";
2760 chomp(my $filename = <STDIN>);
2761 $cred->cert_file($filename);
2762 $cred->may_save($may_save);
2763 $SVN::_Core::SVN_NO_ERROR;
2764}
2765
2766sub _ssl_client_cert_pw_prompt {
2767 my ($cred, $realm, $may_save, $pool) = @_;
2768 $may_save = undef if $_no_auth_cache;
2769 $cred->password(_read_password("Password: ", $realm));
2770 $cred->may_save($may_save);
2771 $SVN::_Core::SVN_NO_ERROR;
2772}
2773
2774sub _username_prompt {
2775 my ($cred, $realm, $may_save, $pool) = @_;
2776 $may_save = undef if $_no_auth_cache;
2777 if (defined $realm && length $realm) {
2778 print "Authentication realm: $realm\n";
2779 }
2780 my $username;
2781 if (defined $_username) {
2782 $username = $_username;
2783 } else {
2784 print "Username: ";
2785 chomp($username = <STDIN>);
2786 }
2787 $cred->username($username);
2788 $cred->may_save($may_save);
2789 $SVN::_Core::SVN_NO_ERROR;
2790}
2791
2792sub _read_password {
2793 my ($prompt, $realm) = @_;
2794 print $prompt;
2795 require Term::ReadKey;
2796 Term::ReadKey::ReadMode('noecho');
2797 my $password = '';
2798 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2799 last if $key =~ /[\012\015]/; # \n\r
2800 $password .= $key;
2801 }
2802 Term::ReadKey::ReadMode('restore');
2803 print "\n";
2804 $password;
2805}
2806
a5e0cedc
EW
2807sub libsvn_connect {
2808 my ($url) = @_;
747fa12c
EW
2809 SVN::_Core::svn_config_ensure($_config_dir, undef);
2810 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2811 SVN::Client::get_simple_provider(),
2812 SVN::Client::get_ssl_server_trust_file_provider(),
2813 SVN::Client::get_simple_prompt_provider(
2814 \&_simple_prompt, 2),
2815 SVN::Client::get_ssl_client_cert_prompt_provider(
2816 \&_ssl_client_cert_prompt, 2),
2817 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2818 \&_ssl_client_cert_pw_prompt, 2),
2819 SVN::Client::get_username_provider(),
2820 SVN::Client::get_ssl_server_trust_prompt_provider(
2821 \&_ssl_server_trust_prompt),
2822 SVN::Client::get_username_prompt_provider(
2823 \&_username_prompt, 2),
2824 ]);
6f23ebf6 2825 my $config = SVN::Core::config_get_config($_config_dir);
747fa12c 2826 my $ra = SVN::Ra->new(url => $url, auth => $baton,
6f23ebf6 2827 config => $config,
747fa12c
EW
2828 pool => SVN::Pool->new,
2829 auth_provider_callbacks => $callbacks);
2830 $ra->{svn_path} = $url;
2831 $ra->{repos_root} = $ra->get_repos_root;
2832 $ra->{svn_path} =~ s#^\Q$ra->{repos_root}\E/*##;
2833 push @repo_path_split_cache, qr/^(\Q$ra->{repos_root}\E)/;
2834 return $ra;
2835}
2836
2837sub libsvn_dup_ra {
2838 my ($ra) = @_;
6f23ebf6
EW
2839 SVN::Ra->new(map { $_ => $ra->{$_} } qw/config url
2840 auth auth_provider_callbacks repos_root svn_path/);
a5e0cedc
EW
2841}
2842
2843sub libsvn_get_file {
75bd7e37 2844 my ($gui, $f, $rev, $chg) = @_;
747fa12c 2845 $f =~ s#^/##;
75bd7e37 2846 print "\t$chg\t$f\n" unless $_q;
a5e0cedc 2847
968bdf1f 2848 my ($hash, $pid, $in, $out);
a5e0cedc 2849 my $pool = SVN::Pool->new;
968bdf1f
EW
2850 defined($pid = open3($in, $out, '>&STDERR',
2851 qw/git-hash-object -w --stdin/)) or croak $!;
dc62e25c
EW
2852 # redirect STDOUT for SVN 1.1.x compatibility
2853 open my $stdout, '>&', \*STDOUT or croak $!;
2854 open STDOUT, '>&', $in or croak $!;
dc62e25c 2855 my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
968bdf1f 2856 $in->flush == 0 or croak $!;
dc62e25c 2857 open STDOUT, '>&', $stdout or croak $!;
968bdf1f 2858 close $in or croak $!;
dc62e25c 2859 close $stdout or croak $!;
a5e0cedc 2860 $pool->clear;
968bdf1f
EW
2861 chomp($hash = do { local $/; <$out> });
2862 close $out or croak $!;
2863 waitpid $pid, 0;
2864 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2865
2866 my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
a5e0cedc
EW
2867 if (exists $props->{'svn:special'}) {
2868 $mode = '120000';
968bdf1f 2869 my $link = `git-cat-file blob $hash`;
a5e0cedc
EW
2870 $link =~ s/^link // or die "svn:special file with contents: <",
2871 $link, "> is not understood\n";
968bdf1f
EW
2872 defined($pid = open3($in, $out, '>&STDERR',
2873 qw/git-hash-object -w --stdin/)) or croak $!;
2874 print $in $link;
2875 $in->flush == 0 or croak $!;
2876 close $in or croak $!;
2877 chomp($hash = do { local $/; <$out> });
2878 close $out or croak $!;
2879 waitpid $pid, 0;
2880 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
a5e0cedc 2881 }
747fa12c 2882 print $gui $mode,' ',$hash,"\t",$f,"\0" or croak $!;
a5e0cedc
EW
2883}
2884
2885sub libsvn_log_entry {
2886 my ($rev, $author, $date, $msg, $parents) = @_;
2887 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2888 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2889 or die "Unable to parse date: $date\n";
2890 if (defined $_authors && ! defined $users{$author}) {
2891 die "Author: $author not defined in $_authors file\n";
2892 }
308906fa 2893 $msg = '' if ($rev == 0 && !defined $msg);
a5e0cedc
EW
2894 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2895 author => $author, msg => $msg."\n", parents => $parents || [] }
2896}
2897
2898sub process_rm {
2899 my ($gui, $last_commit, $f) = @_;
a5e0cedc
EW
2900 # remove entire directories.
2901 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2902 defined(my $pid = open my $ls, '-|') or croak $!;
2903 if (!$pid) {
2904 exec(qw/git-ls-tree -r --name-only -z/,
2905 $last_commit,'--',$f) or croak $!;
2906 }
2907 local $/ = "\0";
2908 while (<$ls>) {
2909 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2910 }
cf7424b0 2911 close $ls or croak $?;
a5e0cedc
EW
2912 } else {
2913 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2914 }
2915}
2916
2917sub libsvn_fetch {
2918 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2919 open my $gui, '| git-update-index -z --index-info' or croak $!;
2920 my @amr;
747fa12c 2921 my $p = $SVN->{svn_path};
a5e0cedc
EW
2922 foreach my $f (keys %$paths) {
2923 my $m = $paths->{$f}->action();
efe4631d
EW
2924 if (length $p) {
2925 $f =~ s#^/\Q$p\E/##;
2926 next if $f =~ m#^/#;
2927 } else {
2928 $f =~ s#^/##;
2929 }
a5e0cedc 2930 if ($m =~ /^[DR]$/) {
80f50749 2931 print "\t$m\t$f\n" unless $_q;
a5e0cedc
EW
2932 process_rm($gui, $last_commit, $f);
2933 next if $m eq 'D';
2934 # 'R' can be file replacements, too, right?
2935 }
2936 my $pool = SVN::Pool->new;
2937 my $t = $SVN->check_path($f, $rev, $pool);
2938 if ($t == $SVN::Node::file) {
2939 if ($m =~ /^[AMR]$/) {
80f50749 2940 push @amr, [ $m, $f ];
a5e0cedc
EW
2941 } else {
2942 die "Unrecognized action: $m, ($f r$rev)\n";
2943 }
d0d8f7dc
EW
2944 } elsif ($t == $SVN::Node::dir && $m =~ /^[AR]$/) {
2945 my @traversed = ();
2946 libsvn_traverse($gui, '', $f, $rev, \@traversed);
2947 foreach (@traversed) {
2948 push @amr, [ $m, $_ ]
2949 }
a5e0cedc
EW
2950 }
2951 $pool->clear;
2952 }
80f50749 2953 foreach (@amr) {
75bd7e37 2954 libsvn_get_file($gui, $_->[1], $rev, $_->[0]);
80f50749 2955 }
cf7424b0 2956 close $gui or croak $?;
a5e0cedc
EW
2957 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2958}
2959
2960sub svn_grab_base_rev {
2961 defined(my $pid = open my $fh, '-|') or croak $!;
2962 if (!$pid) {
2963 open my $null, '>', '/dev/null' or croak $!;
2964 open STDERR, '>&', $null or croak $!;
2965 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2966 or croak $!;
2967 }
2968 chomp(my $c = do { local $/; <$fh> });
2969 close $fh;
2970 if (defined $c && length $c) {
c1927a85 2971 my ($url, $rev, $uuid) = cmt_metadata($c);
a00439ac
EW
2972 return ($rev, $c) if defined $rev;
2973 }
2974 if ($_no_metadata) {
2975 my $offset = -41; # from tail
2976 my $rl;
2977 open my $fh, '<', $REVDB or
2978 die "--no-metadata specified and $REVDB not readable\n";
2979 seek $fh, $offset, 2;
2980 $rl = readline $fh;
2981 defined $rl or return (undef, undef);
2982 chomp $rl;
2983 while ($c ne $rl && tell $fh != 0) {
2984 $offset -= 41;
2985 seek $fh, $offset, 2;
2986 $rl = readline $fh;
2987 defined $rl or return (undef, undef);
2988 chomp $rl;
2989 }
2990 my $rev = tell $fh;
2991 croak $! if ($rev < -1);
2992 $rev = ($rev - 41) / 41;
2993 close $fh or croak $!;
a5e0cedc
EW
2994 return ($rev, $c);
2995 }
2996 return (undef, undef);
2997}
2998
2999sub libsvn_parse_revision {
3000 my $base = shift;
3001 my $head = $SVN->get_latest_revnum();
3002 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
3003 return ($base + 1, $head) if (defined $base);
3004 return (0, $head);
3005 }
3006 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
3007 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
3008 if ($_revision =~ /^BASE:(\d+)$/) {
3009 return ($base + 1, $1) if (defined $base);
3010 return (0, $head);
3011 }
3012 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
3013 die "revision argument: $_revision not understood by git-svn\n",
3014 "Try using the command-line svn client instead\n";
3015}
3016
3017sub libsvn_traverse {
d0d8f7dc 3018 my ($gui, $pfx, $path, $rev, $files) = @_;
747fa12c 3019 my $cwd = length $pfx ? "$pfx/$path" : $path;
a5e0cedc 3020 my $pool = SVN::Pool->new;
747fa12c 3021 $cwd =~ s#^\Q$SVN->{svn_path}\E##;
a5e0cedc
EW
3022 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
3023 foreach my $d (keys %$dirent) {
3024 my $t = $dirent->{$d}->kind;
3025 if ($t == $SVN::Node::dir) {
d0d8f7dc 3026 libsvn_traverse($gui, $cwd, $d, $rev, $files);
a5e0cedc 3027 } elsif ($t == $SVN::Node::file) {
d0d8f7dc
EW
3028 my $file = "$cwd/$d";
3029 if (defined $files) {
3030 push @$files, $file;
3031 } else {
75bd7e37 3032 libsvn_get_file($gui, $file, $rev, 'A');
d0d8f7dc 3033 }
a5e0cedc
EW
3034 }
3035 }
3036 $pool->clear;
3037}
3038
3039sub libsvn_traverse_ignore {
3040 my ($fh, $path, $r) = @_;
3041 $path =~ s#^/+##g;
3042 my $pool = SVN::Pool->new;
3043 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
3044 my $p = $path;
747fa12c 3045 $p =~ s#^\Q$SVN->{svn_path}\E/##;
a5e0cedc
EW
3046 print $fh length $p ? "\n# $p\n" : "\n# /\n";
3047 if (my $s = $props->{'svn:ignore'}) {
3048 $s =~ s/[\r\n]+/\n/g;
3049 chomp $s;
3050 if (length $p == 0) {
3051 $s =~ s#\n#\n/$p#g;
3052 print $fh "/$s\n";
3053 } else {
3054 $s =~ s#\n#\n/$p/#g;
3055 print $fh "/$p/$s\n";
3056 }
3057 }
3058 foreach (sort keys %$dirent) {
3059 next if $dirent->{$_}->kind != $SVN::Node::dir;
3060 libsvn_traverse_ignore($fh, "$path/$_", $r);
3061 }
3062 $pool->clear;
3063}
3064
42d32870
EW
3065sub revisions_eq {
3066 my ($path, $r0, $r1) = @_;
3067 return 1 if $r0 == $r1;
3068 my $nr = 0;
3069 if ($_use_lib) {
3070 # should be OK to use Pool here (r1 - r0) should be small
3071 my $pool = SVN::Pool->new;
747fa12c 3072 libsvn_get_log($SVN, [$path], $r0, $r1,
dc62e25c 3073 0, 1, 1, sub {$nr++}, $pool);
42d32870
EW
3074 $pool->clear;
3075 } else {
3076 my ($url, undef) = repo_path_split($SVN_URL);
3077 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
3078 while (next_log_entry($svn_log)) { $nr++ }
3079 close $svn_log->{fh};
3080 }
3081 return 0 if ($nr > 1);
3082 return 1;
3083}
3084
3085sub libsvn_find_parent_branch {
a5e0cedc 3086 my ($paths, $rev, $author, $date, $msg) = @_;
747fa12c 3087 my $svn_path = '/'.$SVN->{svn_path};
a5e0cedc
EW
3088
3089 # look for a parent from another branch:
cf7424b0
EW
3090 my $i = $paths->{$svn_path} or return;
3091 my $branch_from = $i->copyfrom_path or return;
3092 my $r = $i->copyfrom_rev;
3093 print STDERR "Found possible branch point: ",
3094 "$branch_from => $svn_path, $r\n";
3095 $branch_from =~ s#^/##;
a00439ac
EW
3096 my $l_map = {};
3097 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
747fa12c 3098 my $url = $SVN->{repos_root};
cf7424b0 3099 defined $l_map->{$url} or return;
a00439ac
EW
3100 my $id = $l_map->{$url}->{$branch_from};
3101 if (!defined $id && $_follow_parent) {
3102 print STDERR "Following parent: $branch_from\@$r\n";
3103 # auto create a new branch and follow it
3104 $id = basename($branch_from);
3105 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
3106 while (-r "$GIT_DIR/svn/$id") {
3107 # just grow a tail if we're not unique enough :x
3108 $id .= '-';
3109 }
3110 }
3111 return unless defined $id;
3112
cf7424b0 3113 my ($r0, $parent) = find_rev_before($r,$id,1);
a00439ac
EW
3114 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
3115 defined(my $pid = fork) or croak $!;
3116 if (!$pid) {
3117 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
3118 init_vars();
3119 $SVN_URL = "$url/$branch_from";
747fa12c 3120 $SVN = undef;
a00439ac
EW
3121 setup_git_svn();
3122 # we can't assume SVN_URL exists at r+1:
3123 $_revision = "0:$r";
3124 fetch_lib();
3125 exit 0;
3126 }
3127 waitpid $pid, 0;
3128 croak $? if $?;
3129 ($r0, $parent) = find_rev_before($r,$id,1);
3130 }
cf7424b0
EW
3131 return unless (defined $r0 && defined $parent);
3132 if (revisions_eq($branch_from, $r0, $r)) {
3133 unlink $GIT_SVN_INDEX;
a00439ac 3134 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
cf7424b0
EW
3135 sys(qw/git-read-tree/, $parent);
3136 return libsvn_fetch($parent, $paths, $rev,
3137 $author, $date, $msg);
3138 }
3139 print STDERR "Nope, branch point not imported or unknown\n";
42d32870
EW
3140 return undef;
3141}
3142
dc62e25c
EW
3143sub libsvn_get_log {
3144 my ($ra, @args) = @_;
3145 if ($SVN::Core::VERSION le '1.2.0') {
3146 splice(@args, 3, 1);
3147 }
3148 $ra->get_log(@args);
3149}
3150
42d32870
EW
3151sub libsvn_new_tree {
3152 if (my $log_entry = libsvn_find_parent_branch(@_)) {
3153 return $log_entry;
3154 }
3155 my ($paths, $rev, $author, $date, $msg) = @_;
a5e0cedc 3156 open my $gui, '| git-update-index -z --index-info' or croak $!;
747fa12c 3157 libsvn_traverse($gui, '', $SVN->{svn_path}, $rev);
cf7424b0 3158 close $gui or croak $?;
a5e0cedc
EW
3159 return libsvn_log_entry($rev, $author, $date, $msg);
3160}
3161
3162sub find_graft_path_commit {
3163 my ($tree_paths, $p1, $r1) = @_;
3164 foreach my $x (keys %$tree_paths) {
3165 next unless ($p1 =~ /^\Q$x\E/);
3166 my $i = $tree_paths->{$x};
42d32870
EW
3167 my ($r0, $parent) = find_rev_before($r1,$i,1);
3168 return $parent if (defined $r0 && $r0 == $r1);
a5e0cedc
EW
3169 print STDERR "r$r1 of $i not imported\n";
3170 next;
3171 }
3172 return undef;
3173}
3174
3175sub find_graft_path_parents {
3176 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
3177 foreach my $x (keys %$tree_paths) {
3178 next unless ($p0 =~ /^\Q$x\E/);
3179 my $i = $tree_paths->{$x};
42d32870
EW
3180 my ($r, $parent) = find_rev_before($r0, $i, 1);
3181 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
c1927a85
EW
3182 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
3183 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
3184 next if ($url_a && $url_b && $url_a eq $url_b &&
3185 $uuid_b eq $uuid_a);
42d32870 3186 $grafts->{$c}->{$parent} = 1;
a5e0cedc 3187 }
a5e0cedc
EW
3188 }
3189}
3190
3191sub libsvn_graft_file_copies {
3192 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
3193 foreach (keys %$paths) {
3194 my $i = $paths->{$_};
3195 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
3196 $i->copyfrom_rev);
3197 next unless (defined $p0 && defined $r0);
3198
3199 my $p1 = $_;
3200 $p1 =~ s#^/##;
3201 $p0 =~ s#^/##;
3202 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
3203 next unless $c;
3204 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
3205 }
3206}
3207
3208sub set_index {
3209 my $old = $ENV{GIT_INDEX_FILE};
3210 $ENV{GIT_INDEX_FILE} = shift;
3211 return $old;
3212}
3213
3214sub restore_index {
3215 my ($old) = @_;
3216 if (defined $old) {
3217 $ENV{GIT_INDEX_FILE} = $old;
3218 } else {
3219 delete $ENV{GIT_INDEX_FILE};
3220 }
3221}
3222
3223sub libsvn_commit_cb {
3224 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
42d32870 3225 if ($_optimize_commits && $rev == ($r_last + 1)) {
a5e0cedc
EW
3226 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
3227 $log->{tree} = get_tree_from_treeish($c);
3228 my $cmt = git_commit($log, $cmt_last, $c);
3229 my @diff = safe_qx('git-diff-tree', $cmt, $c);
3230 if (@diff) {
3231 print STDERR "Trees differ: $cmt $c\n",
3232 join('',@diff),"\n";
3233 exit 1;
3234 }
3235 } else {
cf7424b0 3236 fetch("$rev=$c");
a5e0cedc
EW
3237 }
3238}
3239
3240sub libsvn_ls_fullurl {
3241 my $fullurl = shift;
747fa12c 3242 $SVN ||= libsvn_connect($fullurl);
a5e0cedc
EW
3243 my @ret;
3244 my $pool = SVN::Pool->new;
747fa12c 3245 my ($dirent, undef, undef) = $SVN->get_dir($SVN->{svn_path},
a5e0cedc
EW
3246 $SVN->get_latest_revnum, $pool);
3247 foreach my $d (keys %$dirent) {
3248 if ($dirent->{$d}->kind == $SVN::Node::dir) {
3249 push @ret, "$d/"; # add '/' for compat with cli svn
3250 }
3251 }
3252 $pool->clear;
3253 return @ret;
3254}
3255
3256
3257sub libsvn_skip_unknown_revs {
3258 my $err = shift;
3259 my $errno = $err->apr_err();
3260 # Maybe the branch we're tracking didn't
3261 # exist when the repo started, so it's
3262 # not an error if it doesn't, just continue
3263 #
3264 # Wonderfully consistent library, eh?
3265 # 160013 - svn:// and file://
3266 # 175002 - http(s)://
747fa12c 3267 # 175007 - http(s):// (this repo required authorization, too...)
a5e0cedc 3268 # More codes may be discovered later...
747fa12c 3269 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a5e0cedc
EW
3270 return;
3271 }
3272 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3273};
3274
42d32870
EW
3275# Tie::File seems to be prone to offset errors if revisions get sparse,
3276# it's not that fast, either. Tie::File is also not in Perl 5.6. So
3277# one of my favorite modules is out :< Next up would be one of the DBM
3278# modules, but I'm not sure which is most portable... So I'll just
3279# go with something that's plain-text, but still capable of
3280# being randomly accessed. So here's my ultra-simple fixed-width
3281# database. All records are 40 characters + "\n", so it's easy to seek
3282# to a revision: (41 * rev) is the byte offset.
3283# A record of 40 0s denotes an empty revision.
3284# And yes, it's still pretty fast (faster than Tie::File).
3285sub revdb_set {
3286 my ($file, $rev, $commit) = @_;
3287 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
3288 open my $fh, '+<', $file or croak $!;
3289 my $offset = $rev * 41;
3290 # assume that append is the common case:
3291 seek $fh, 0, 2 or croak $!;
3292 my $pos = tell $fh;
3293 if ($pos < $offset) {
3294 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
3295 }
3296 seek $fh, $offset, 0 or croak $!;
3297 print $fh $commit,"\n";
3298 close $fh or croak $!;
3299}
3300
3301sub revdb_get {
3302 my ($file, $rev) = @_;
3303 my $ret;
3304 my $offset = $rev * 41;
3305 open my $fh, '<', $file or croak $!;
3306 seek $fh, $offset, 0;
3307 if (tell $fh == $offset) {
3308 $ret = readline $fh;
3309 if (defined $ret) {
3310 chomp $ret;
3311 $ret = undef if ($ret =~ /^0{40}$/);
3312 }
3313 }
3314 close $fh or croak $!;
3315 return $ret;
3316}
3317
1a82e793
EW
3318sub copy_remote_ref {
3319 my $origin = $_cp_remote ? $_cp_remote : 'origin';
3320 my $ref = "refs/remotes/$GIT_SVN";
3321 if (safe_qx('git-ls-remote', $origin, $ref)) {
3322 sys(qw/git fetch/, $origin, "$ref:$ref");
a35a0458 3323 } elsif ($_cp_remote && !$_upgrade) {
1a82e793
EW
3324 die "Unable to find remote reference: ",
3325 "refs/remotes/$GIT_SVN on $origin\n";
3326 }
3327}
3328
a5e0cedc
EW
3329package SVN::Git::Editor;
3330use vars qw/@ISA/;
3331use strict;
3332use warnings;
3333use Carp qw/croak/;
3334use IO::File;
3335
3336sub new {
3337 my $class = shift;
3338 my $git_svn = shift;
3339 my $self = SVN::Delta::Editor->new(@_);
3340 bless $self, $class;
3341 foreach (qw/svn_path c r ra /) {
3342 die "$_ required!\n" unless (defined $git_svn->{$_});
3343 $self->{$_} = $git_svn->{$_};
3344 }
3345 $self->{pool} = SVN::Pool->new;
3346 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3347 $self->{rm} = { };
3348 require Digest::MD5;
3349 return $self;
3350}
3351
3352sub split_path {
3353 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3354}
3355
3356sub repo_path {
747fa12c 3357 (defined $_[1] && length $_[1]) ? $_[1] : ''
a5e0cedc
EW
3358}
3359
3360sub url_path {
3361 my ($self, $path) = @_;
3362 $self->{ra}->{url} . '/' . $self->repo_path($path);
3363}
3364
3365sub rmdirs {
80f50749 3366 my ($self, $q) = @_;
a5e0cedc
EW
3367 my $rm = $self->{rm};
3368 delete $rm->{''}; # we never delete the url we're tracking
3369 return unless %$rm;
3370
3371 foreach (keys %$rm) {
3372 my @d = split m#/#, $_;
3373 my $c = shift @d;
3374 $rm->{$c} = 1;
3375 while (@d) {
3376 $c .= '/' . shift @d;
3377 $rm->{$c} = 1;
3378 }
3379 }
3380 delete $rm->{$self->{svn_path}};
3381 delete $rm->{''}; # we never delete the url we're tracking
3382 return unless %$rm;
3383
3384 defined(my $pid = open my $fh,'-|') or croak $!;
3385 if (!$pid) {
3386 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
3387 }
3388 local $/ = "\0";
3389 while (<$fh>) {
3390 chomp;
747fa12c 3391 my @dn = split m#/#, $_;
c07eee1f
EW
3392 while (pop @dn) {
3393 delete $rm->{join '/', @dn};
3394 }
3395 unless (%$rm) {
3396 close $fh;
3397 return;
3398 }
a5e0cedc 3399 }
c07eee1f
EW
3400 close $fh;
3401
a5e0cedc
EW
3402 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3403 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3404 $self->close_directory($bat->{$d}, $p);
3405 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
80f50749 3406 print "\tD+\t/$d/\n" unless $q;
a5e0cedc
EW
3407 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3408 delete $bat->{$d};
3409 }
3410}
3411
3412sub open_or_add_dir {
3413 my ($self, $full_path, $baton) = @_;
3414 my $p = SVN::Pool->new;
3415 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3416 $p->clear;
3417 if ($t == $SVN::Node::none) {
3418 return $self->add_directory($full_path, $baton,
3419 undef, -1, $self->{pool});
3420 } elsif ($t == $SVN::Node::dir) {
3421 return $self->open_directory($full_path, $baton,
3422 $self->{r}, $self->{pool});
3423 }
3424 print STDERR "$full_path already exists in repository at ",
3425 "r$self->{r} and it is not a directory (",
3426 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3427 exit 1;
3428}
3429
3430sub ensure_path {
3431 my ($self, $path) = @_;
3432 my $bat = $self->{bat};
3433 $path = $self->repo_path($path);
3434 return $bat->{''} unless (length $path);
3435 my @p = split m#/+#, $path;
3436 my $c = shift @p;
3437 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3438 while (@p) {
3439 my $c0 = $c;
3440 $c .= '/' . shift @p;
3441 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3442 }
3443 return $bat->{$c};
3444}
3445
3446sub A {
80f50749 3447 my ($self, $m, $q) = @_;
a5e0cedc
EW
3448 my ($dir, $file) = split_path($m->{file_b});
3449 my $pbat = $self->ensure_path($dir);
3450 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3451 undef, -1);
80f50749 3452 print "\tA\t$m->{file_b}\n" unless $q;
a5e0cedc
EW
3453 $self->chg_file($fbat, $m);
3454 $self->close_file($fbat,undef,$self->{pool});
3455}
3456
3457sub C {
80f50749 3458 my ($self, $m, $q) = @_;
a5e0cedc
EW
3459 my ($dir, $file) = split_path($m->{file_b});
3460 my $pbat = $self->ensure_path($dir);
3461 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3462 $self->url_path($m->{file_a}), $self->{r});
80f50749 3463 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
a5e0cedc
EW
3464 $self->chg_file($fbat, $m);
3465 $self->close_file($fbat,undef,$self->{pool});
3466}
3467
3468sub delete_entry {
3469 my ($self, $path, $pbat) = @_;
3470 my $rpath = $self->repo_path($path);
3471 my ($dir, $file) = split_path($rpath);
3472 $self->{rm}->{$dir} = 1;
3473 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3474}
3475
3476sub R {
80f50749 3477 my ($self, $m, $q) = @_;
a5e0cedc
EW
3478 my ($dir, $file) = split_path($m->{file_b});
3479 my $pbat = $self->ensure_path($dir);
3480 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3481 $self->url_path($m->{file_a}), $self->{r});
80f50749 3482 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
a5e0cedc
EW
3483 $self->chg_file($fbat, $m);
3484 $self->close_file($fbat,undef,$self->{pool});
3485
3486 ($dir, $file) = split_path($m->{file_a});
3487 $pbat = $self->ensure_path($dir);
3488 $self->delete_entry($m->{file_a}, $pbat);
3489}
3490
3491sub M {
80f50749 3492 my ($self, $m, $q) = @_;
a5e0cedc
EW
3493 my ($dir, $file) = split_path($m->{file_b});
3494 my $pbat = $self->ensure_path($dir);
3495 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3496 $pbat,$self->{r},$self->{pool});
80f50749 3497 print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
a5e0cedc
EW
3498 $self->chg_file($fbat, $m);
3499 $self->close_file($fbat,undef,$self->{pool});
3500}
3501
3502sub T { shift->M(@_) }
3503
3504sub change_file_prop {
3505 my ($self, $fbat, $pname, $pval) = @_;
3506 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3507}
3508
3509sub chg_file {
3510 my ($self, $fbat, $m) = @_;
3511 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3512 $self->change_file_prop($fbat,'svn:executable','*');
3513 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3514 $self->change_file_prop($fbat,'svn:executable',undef);
3515 }
3516 my $fh = IO::File->new_tmpfile or croak $!;
3517 if ($m->{mode_b} =~ /^120/) {
3518 print $fh 'link ' or croak $!;
3519 $self->change_file_prop($fbat,'svn:special','*');
3520 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3521 $self->change_file_prop($fbat,'svn:special',undef);
3522 }
3523 defined(my $pid = fork) or croak $!;
3524 if (!$pid) {
3525 open STDOUT, '>&', $fh or croak $!;
3526 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3527 }
3528 waitpid $pid, 0;
3529 croak $? if $?;
3530 $fh->flush == 0 or croak $!;
3531 seek $fh, 0, 0 or croak $!;
3532
3533 my $md5 = Digest::MD5->new;
3534 $md5->addfile($fh) or croak $!;
3535 seek $fh, 0, 0 or croak $!;
3536
3537 my $exp = $md5->hexdigest;
f7197dff
EW
3538 my $pool = SVN::Pool->new;
3539 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3540 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 3541 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 3542 $pool->clear;
a5e0cedc
EW
3543
3544 close $fh or croak $!;
3545}
3546
3547sub D {
80f50749 3548 my ($self, $m, $q) = @_;
a5e0cedc
EW
3549 my ($dir, $file) = split_path($m->{file_b});
3550 my $pbat = $self->ensure_path($dir);
80f50749 3551 print "\tD\t$m->{file_b}\n" unless $q;
a5e0cedc
EW
3552 $self->delete_entry($m->{file_b}, $pbat);
3553}
3554
3555sub close_edit {
3556 my ($self) = @_;
3557 my ($p,$bat) = ($self->{pool}, $self->{bat});
3558 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3559 $self->close_directory($bat->{$_}, $p);
3560 }
3561 $self->SUPER::close_edit($p);
3562 $p->clear;
3563}
3564
3565sub abort_edit {
3566 my ($self) = @_;
3567 $self->SUPER::abort_edit($self->{pool});
3568 $self->{pool}->clear;
3569}
3570
3397f9df
EW
3571__END__
3572
3573Data structures:
3574
03823184
EW
3575$svn_log hashref (as returned by svn_log_raw)
3576{
3577 fh => file handle of the log file,
3578 state => state of the log file parser (sep/msg/rev/msg_start...)
3579}
3397f9df 3580
03823184 3581$log_msg hashref as returned by next_log_entry($svn_log)
3397f9df
EW
3582{
3583 msg => 'whitespace-formatted log entry
3584', # trailing newline is preserved
3585 revision => '8', # integer
3586 date => '2004-02-24T17:01:44.108345Z', # commit date
3587 author => 'committer name'
3588};
3589
3590
3591@mods = array of diff-index line hashes, each element represents one line
3592 of diff-index output
3593
3594diff-index line ($m hash)
3595{
3596 mode_a => first column of diff-index output, no leading ':',
3597 mode_b => second column of diff-index output,
3598 sha1_b => sha1sum of the final blob,
ac8e0b91 3599 chg => change type [MCRADT],
3397f9df
EW
3600 file_a => original file name of a file (iff chg is 'C' or 'R')
3601 file_b => new/current file name of a file (any chg)
3602}
3603;
a5e0cedc 3604
a00439ac
EW
3605# retval of read_url_paths{,_all}();
3606$l_map = {
3607 # repository root url
3608 'https://svn.musicpd.org' => {
3609 # repository path # GIT_SVN_ID
3610 'mpd/trunk' => 'trunk',
3611 'mpd/tags/0.11.5' => 'tags/0.11.5',
3612 },
3613}
3614
a5e0cedc
EW
3615Notes:
3616 I don't trust the each() function on unless I created %hash myself
3617 because the internal iterator may not have started at base.