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