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