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