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