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