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