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