Fix symlink handling in git-svn, related to PerlIO
[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
9760adcc
EW
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
3397f9df 9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 10$VERSION = '@@GIT_VERSION@@';
13ccd6d4 11
5253dc33 12my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 13$ENV{GIT_DIR} ||= '.git';
9fa00b65 14$Git::SVN::default_repo_id = 'svn';
8b8fc068 15$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 16$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 17
f8c9d1d2 18$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 19$ENV{TZ} = 'UTC';
a00439ac 20$| = 1; # unbuffer STDOUT
3397f9df 21
6fda05ae 22sub fatal (@) { print STDERR @_; exit 1 }
b9c85187
EW
23require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24require SVN::Ra;
25require SVN::Delta;
26if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
28}
d81bf827 29push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
30push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df
EW
32use Carp qw/croak/;
33use IO::File qw//;
34use File::Basename qw/dirname basename/;
35use File::Path qw/mkpath/;
512b620b 36use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 37use IPC::Open3;
336f1714 38use Git;
a5e0cedc 39
336f1714
EW
40BEGIN {
41 my $s;
42 foreach (qw/command command_oneline command_noisy command_output_pipe
43 command_input_pipe command_close_pipe/) {
44 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
706587fc 45 "*Git::SVN::Migration::$_ = ".
f8c9d1d2 46 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
336f1714
EW
47 }
48 eval $s;
49}
50
b9c85187 51my ($SVN);
83e9940a 52
f8c9d1d2
EW
53$sha1 = qr/[a-f\d]{40}/;
54$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 55my ($_stdin, $_help, $_edit,
9760adcc 56 $_message, $_file,
d05d72e0 57 $_template, $_shared,
e98671e5 58 $_version, $_fetch_all,
dee41f3e 59 $_merge, $_strategy, $_dry_run, $_local,
905f8b7d 60 $_prefix, $_no_checkout, $_verbose);
0bed5eaa 61$Git::SVN::_follow_parent = 1;
706587fc
EW
62my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63 'config-dir=s' => \$Git::SVN::Ra::config_dir,
64 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 65my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 66 'authors-file|A=s' => \$_authors,
ecc712dd 67 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
68 'noMetadata' => \$Git::SVN::_no_metadata,
69 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 70 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 71 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 72 'no-checkout' => \$_no_checkout,
80f50749 73 'quiet|q' => \$_q,
ecc712dd
EW
74 'repack-flags|repack-args|repack-opts=s' =>
75 \$Git::SVN::_repack_flags,
706587fc 76 %remote_opts );
36f5b1f0 77
9d55b41a 78my ($_trunk, $_tags, $_branches);
0dfaf0a4 79my %icv;
dadc6d2a
EW
80my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
0dfaf0a4
EW
83 'no-metadata' => sub { $icv{noMetadata} = 1 },
84 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
85 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
86 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
dadc6d2a 87 %remote_opts );
27e9fb8d 88my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
89 'rmdir' => \$SVN::Git::Editor::_rmdir,
90 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
91 'l=i' => \$SVN::Git::Editor::_rename_limit,
92 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 93);
9d55b41a 94
3397f9df 95my %cmd = (
2a3240be 96 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 97 { 'revision|r=s' => \$_revision,
905f8b7d 98 'fetch-all|all' => \$_fetch_all,
e98671e5 99 %fc_opts } ],
0425ea90
EW
100 clone => [ \&cmd_clone, "Initialize and fetch revisions",
101 { 'revision|r=s' => \$_revision,
102 %fc_opts, %init_opts } ],
d2866f9e 103 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 104 " (requires URL argument)",
9d55b41a 105 \%init_opts ],
dadc6d2a
EW
106 'multi-init' => [ \&cmd_multi_init,
107 "Deprecated alias for ".
108 "'$0 init -T<trunk> -b<branches> -t<tags>'",
109 \%init_opts ],
d7ad3bed
EW
110 dcommit => [ \&cmd_dcommit,
111 'Commit several diffs to merge with upstream',
3289e86e
EW
112 { 'merge|m|M' => \$_merge,
113 'strategy|s=s' => \$_strategy,
905f8b7d 114 'verbose|v' => \$_verbose,
3289e86e 115 'dry-run|n' => \$_dry_run,
905f8b7d 116 'fetch-all|all' => \$_fetch_all,
4b155223 117 %cmt_opts, %fc_opts } ],
1ce255dc
EW
118 'set-tree' => [ \&cmd_set_tree,
119 "Set an SVN repository to a git tree-ish",
120 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
5969cbe1 121 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
a5e0cedc 122 { 'revision|r=i' => \$_revision } ],
1c8443b0 123 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
124 "Deprecated alias for $0 fetch --all",
125 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
126 'migrate' => [ sub { },
127 # no-op, we automatically run this anyways,
706587fc
EW
128 'Migrate configuration/metadata/layout from
129 previous versions of git-svn',
a836a0e1
EW
130 { 'minimize' => \$Git::SVN::Migration::_minimize,
131 %remote_opts } ],
f8c9d1d2
EW
132 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
133 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 134 'revision|r=s' => \$_revision,
f8c9d1d2
EW
135 'verbose|v' => \$Git::SVN::Log::verbose,
136 'incremental' => \$Git::SVN::Log::incremental,
137 'oneline' => \$Git::SVN::Log::oneline,
138 'show-commit' => \$Git::SVN::Log::show_commit,
139 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 140 'authors-file|A=s' => \$_authors,
f8c9d1d2
EW
141 'color' => \$Git::SVN::Log::color,
142 'pager=s' => \$Git::SVN::Log::pager,
79bb8d88 143 } ],
26e60160
AR
144 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
145 { } ],
905f8b7d
EW
146 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
147 { 'merge|m|M' => \$_merge,
148 'verbose|v' => \$_verbose,
149 'strategy|s=s' => \$_strategy,
dee41f3e 150 'local|l' => \$_local,
905f8b7d
EW
151 'fetch-all|all' => \$_fetch_all,
152 %fc_opts } ],
44320b9e
EW
153 'commit-diff' => [ \&cmd_commit_diff,
154 'Commit a diff between two trees',
27e9fb8d
EW
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);
c284914a 173Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
9760adcc
EW
174my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
175 'minimize-connections' => \$Git::SVN::Migration::_minimize,
176 'id|i=s' => \$Git::SVN::default_ref_id,
befc9adc
EW
177 'svn-remote|remote|R=s' => sub {
178 $Git::SVN::no_reuse_existing = 1;
179 $Git::SVN::default_repo_id = $_[1] });
c284914a 180exit 1 if (!$rv && $cmd && $cmd ne 'log');
6f0783cf 181
3397f9df 182usage(0) if $_help;
551ce28f 183version() if $_version;
eeb0abe0
EW
184usage(1) unless defined $cmd;
185load_authors() if $_authors;
5253dc33
EW
186
187# make sure we're always running
188unless ($cmd =~ /(?:clone|init|multi-init)$/) {
189 unless (-d $ENV{GIT_DIR}) {
190 if ($git_dir_user_set) {
191 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
192 "but it is not a directory\n";
193 }
194 my $git_dir = delete $ENV{GIT_DIR};
195 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
196 unless (length $cdup) {
197 die "Already at toplevel, but $git_dir ",
198 "not found '$cdup'\n";
199 }
200 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
201 unless (-d $git_dir) {
202 die "$git_dir still not found after going to ",
203 "'$cdup'\n";
204 }
205 $ENV{GIT_DIR} = $git_dir;
206 }
207}
0425ea90 208unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
209 Git::SVN::Migration::migration_check();
210}
ecc712dd 211Git::SVN::init_vars();
b805b44a
EW
212eval {
213 Git::SVN::verify_remotes_sanity();
214 $cmd{$cmd}->[0]->(@ARGV);
215};
216fatal $@ if $@;
1e889ef3 217post_fetch_checkout();
3397f9df
EW
218exit 0;
219
220####################### primary functions ######################
221sub usage {
222 my $exit = shift || 0;
223 my $fd = $exit ? \*STDERR : \*STDOUT;
224 print $fd <<"";
225git-svn - bidirectional operations between a single Subversion tree and git
226Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
227
228 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
229
230 foreach (sort keys %cmd) {
448c81b4 231 next if $cmd && $cmd ne $_;
a836a0e1 232 next if /^multi-/; # don't show deprecated commands
b203b769 233 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4 234 foreach (keys %{$cmd{$_}->[2]}) {
512b620b
EW
235 # mixed-case options are for .git/config only
236 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 237 # prints out arguments as they should be passed:
b8c92cad 238 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 239 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
240 "--$_" : "-$_" }
241 split /\|/,$_)," $x\n";
242 }
3397f9df
EW
243 }
244 print $fd <<"";
448c81b4
EW
245\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
246arbitrary identifier if you're tracking multiple SVN branches/repositories in
247one git repository and want to keep them separate. See git-svn(1) for more
248information.
3397f9df
EW
249
250 exit $exit;
251}
252
551ce28f 253sub version {
7d60ab2c 254 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
255 exit 0;
256}
257
8164b652
EW
258sub do_git_init_db {
259 unless (-d $ENV{GIT_DIR}) {
260 my @init_db = ('init');
261 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
262 if (defined $_shared) {
263 if ($_shared =~ /[a-z]/) {
264 push @init_db, "--shared=$_shared";
265 } else {
266 push @init_db, "--shared";
267 }
268 }
8164b652
EW
269 command_noisy(@init_db);
270 }
0dfaf0a4
EW
271 my $set;
272 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
273 foreach my $i (keys %icv) {
274 die "'$set' and '$i' cannot both be set\n" if $set;
275 next unless defined $icv{$i};
276 command_noisy('config', "$pfx.$i", $icv{$i});
277 $set = $i;
278 }
8164b652
EW
279}
280
dadc6d2a
EW
281sub init_subdir {
282 my $repo_path = shift or return;
283 mkpath([$repo_path]) unless -d $repo_path;
284 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 285 $ENV{GIT_DIR} = '.git';
dadc6d2a
EW
286}
287
0425ea90
EW
288sub cmd_clone {
289 my ($url, $path) = @_;
290 if (!defined $path &&
291 (defined $_trunk || defined $_branches || defined $_tags) &&
292 $url !~ m#^[a-z\+]+://#) {
293 $path = $url;
294 }
0425ea90 295 $path = basename($url) if !defined $path || !length $path;
f30603fc 296 cmd_init($url, $path);
0425ea90
EW
297 Git::SVN::fetch_all($Git::SVN::default_repo_id);
298}
299
d2866f9e 300sub cmd_init {
dadc6d2a
EW
301 if (defined $_trunk || defined $_branches || defined $_tags) {
302 return cmd_multi_init(@_);
03e0ea87 303 }
dadc6d2a
EW
304 my $url = shift or die "SVN repository location required ",
305 "as a command-line argument\n";
306 init_subdir(@_);
8164b652 307 do_git_init_db();
03e0ea87 308
706587fc 309 Git::SVN->init($url);
3397f9df
EW
310}
311
2a3240be 312sub cmd_fetch {
e98671e5
EW
313 if (grep /^\d+=./, @_) {
314 die "'<rev>=<commit>' fetch arguments are ",
315 "no longer supported.\n";
07a1c950 316 }
e98671e5
EW
317 my ($remote) = @_;
318 if (@_ > 1) {
905f8b7d 319 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
320 }
321 $remote ||= $Git::SVN::default_repo_id;
322 if ($_fetch_all) {
323 cmd_multi_fetch();
324 } else {
325 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 326 }
2a3240be
EW
327}
328
1ce255dc 329sub cmd_set_tree {
3397f9df
EW
330 my (@commits) = @_;
331 if ($_stdin || !@commits) {
332 print "Reading from stdin...\n";
333 @commits = ();
334 while (<STDIN>) {
1ca72aef 335 if (/\b($sha1_short)\b/o) {
3397f9df
EW
336 unshift @commits, $1;
337 }
338 }
339 }
340 my @revs;
8de010ad 341 foreach my $c (@commits) {
aef4e921 342 my @tmp = command('rev-parse',$c);
8de010ad
EW
343 if (scalar @tmp == 1) {
344 push @revs, $tmp[0];
345 } elsif (scalar @tmp > 1) {
aef4e921 346 push @revs, reverse(command('rev-list',@tmp));
8de010ad 347 } else {
1ce255dc 348 fatal "Failed to rev-parse $c\n";
8de010ad 349 }
3397f9df 350 }
1ce255dc
EW
351 my $gs = Git::SVN->new;
352 my ($r_last, $cmt_last) = $gs->last_rev_commit;
353 $gs->fetch;
97f6987a 354 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
355 fatal "There are new revisions that were fetched ",
356 "and need to be merged (or acknowledged) ",
357 "before committing.\nlast rev: $r_last\n",
358 " current: $gs->{last_rev}\n";
a5e0cedc 359 }
1ce255dc
EW
360 $gs->set_tree($_) foreach @revs;
361 print "Done committing ",scalar @revs," revisions to SVN\n";
a5e0cedc 362}
8f22562c 363
d7ad3bed
EW
364sub cmd_dcommit {
365 my $head = shift;
d7ad3bed 366 $head ||= 'HEAD';
a8ae2623 367 my @refs;
13c823fb
EW
368 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
369 unless ($gs) {
a8ae2623 370 die "Unable to determine upstream SVN information from ",
905f8b7d 371 "$head history\n";
a8ae2623 372 }
13c823fb 373 my $c = $refs[-1];
45bf473a 374 my $last_rev;
a8ae2623 375 foreach my $d (@refs) {
aef4e921 376 if (!verify_ref("$d~1")) {
d7ad3bed
EW
377 fatal "Commit $d\n",
378 "has no parent commit, and therefore ",
379 "nothing to diff against.\n",
380 "You should be working from a repository ",
381 "originally created by git-svn\n";
48d044b5 382 }
45bf473a
EW
383 unless (defined $last_rev) {
384 (undef, $last_rev, undef) = cmt_metadata("$d~1");
385 unless (defined $last_rev) {
d7ad3bed
EW
386 fatal "Unable to extract revision information ",
387 "from commit $d~1\n";
45bf473a
EW
388 }
389 }
b22d4497
EW
390 if ($_dry_run) {
391 print "diff-tree $d~1 $d\n";
392 } else {
d7ad3bed 393 my %ed_opts = ( r => $last_rev,
61395354 394 log => get_commit_entry($d)->{log},
a8ae2623 395 ra => Git::SVN::Ra->new($url),
61395354
EW
396 tree_a => "$d~1",
397 tree_b => $d,
398 editor_cb => sub {
399 print "Committed r$_[0]\n";
400 $last_rev = $_[0]; },
a8ae2623 401 svn_path => '');
61395354 402 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed
EW
403 print "No changes\n$d~1 == $d\n";
404 }
b22d4497
EW
405 }
406 }
407 return if $_dry_run;
60d9c97a
EW
408 unless ($gs) {
409 warn "Could not determine fetch information for $url\n",
410 "Will not attempt to fetch and rebase commits.\n",
411 "This probably means you have useSvmProps and should\n",
412 "now resync your SVN::Mirror repository.\n";
413 return;
414 }
905f8b7d 415 $_fetch_all ? $gs->fetch_all : $gs->fetch;
d7ad3bed
EW
416 # we always want to rebase against the current HEAD, not any
417 # head that was passed to us
418 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
b22d4497
EW
419 my @finish;
420 if (@diff) {
905f8b7d 421 @finish = rebase_cmd();
d7ad3bed
EW
422 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
423 "using @finish:\n", "@diff";
b22d4497 424 } else {
d7ad3bed
EW
425 print "No changes between current HEAD and ",
426 $gs->refname, "\nResetting to the latest ",
427 $gs->refname, "\n";
4769489a 428 @finish = qw/reset --mixed/;
b22d4497 429 }
d7ad3bed 430 command_noisy(@finish, $gs->refname);
b22d4497
EW
431}
432
26e60160
AR
433sub cmd_find_rev {
434 my $revision_or_hash = shift;
435 my $result;
436 if ($revision_or_hash =~ /^r\d+$/) {
437 my $desired_revision = substr($revision_or_hash, 1);
438 my ($fh, $ctx) = command_output_pipe('rev-list', 'HEAD');
439 while (my $hash = <$fh>) {
440 chomp($hash);
441 my (undef, $rev, undef) = cmt_metadata($hash);
442 if ($rev && $rev eq $desired_revision) {
443 $result = $hash;
444 last;
445 }
446 }
447 command_close_pipe($fh, $ctx);
448 } else {
449 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
450 $result = $rev;
451 }
452 print "$result\n" if $result;
453}
454
905f8b7d
EW
455sub cmd_rebase {
456 command_noisy(qw/update-index --refresh/);
13c823fb
EW
457 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
458 unless ($gs) {
905f8b7d
EW
459 die "Unable to determine upstream SVN information from ",
460 "working tree history\n";
461 }
905f8b7d
EW
462 if (command(qw/diff-index HEAD --/)) {
463 print STDERR "Cannot rebase with uncommited changes:\n";
464 command_noisy('status');
465 exit 1;
466 }
dee41f3e
EW
467 unless ($_local) {
468 $_fetch_all ? $gs->fetch_all : $gs->fetch;
469 }
905f8b7d
EW
470 command_noisy(rebase_cmd(), $gs->refname);
471}
472
5969cbe1 473sub cmd_show_ignore {
13c823fb
EW
474 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
475 $gs ||= Git::SVN->new;
5969cbe1 476 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
102a0a2d 477 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
a5e0cedc
EW
478}
479
8164b652 480sub cmd_multi_init {
9d55b41a 481 my $url = shift;
98327e58
EW
482 unless (defined $_trunk || defined $_branches || defined $_tags) {
483 usage(1);
9d55b41a 484 }
8164b652 485 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
486 if (defined $url) {
487 $url =~ s#/+$##;
488 init_subdir(@_);
489 }
f30603fc 490 do_git_init_db();
98327e58 491 if (defined $_trunk) {
706587fc
EW
492 my $trunk_ref = $_prefix . 'trunk';
493 # try both old-style and new-style lookups:
494 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 495 unless ($gs_trunk) {
706587fc
EW
496 my ($trunk_url, $trunk_path) =
497 complete_svn_url($url, $_trunk);
498 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
499 undef, $trunk_ref);
98327e58 500 }
c35b96e7 501 }
706587fc 502 return unless defined $_branches || defined $_tags;
e7db67e6
EW
503 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
504 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
505 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
506}
507
1c8443b0 508sub cmd_multi_fetch {
0af9c9f9
EW
509 my $remotes = Git::SVN::read_all_remotes();
510 foreach my $repo_id (sort keys %$remotes) {
db03cd24 511 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
512 Git::SVN::fetch_all($repo_id, $remotes);
513 }
9d55b41a 514 }
9d55b41a
EW
515}
516
44320b9e
EW
517# this command is special because it requires no metadata
518sub cmd_commit_diff {
519 my ($ta, $tb, $url) = @_;
520 my $usage = "Usage: $0 commit-diff -r<revision> ".
521 "<tree-ish> <tree-ish> [<URL>]\n";
522 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 523 my $svn_path;
44320b9e
EW
524 if (!defined $url) {
525 my $gs = eval { Git::SVN->new };
526 if (!$gs) {
527 fatal("Needed URL or usable git-svn --id in ",
528 "the command-line\n", $usage);
529 }
530 $url = $gs->{url};
d3a840dc 531 $svn_path = $gs->{path};
44320b9e
EW
532 }
533 unless (defined $_revision) {
534 fatal("-r|--revision is a required argument\n", $usage);
535 }
536 if (defined $_message && defined $_file) {
537 fatal("Both --message/-m and --file/-F specified ",
538 "for the commit message.\n",
539 "I have no idea what you mean\n");
540 }
541 if (defined $_file) {
542 $_message = file_to_s($_file);
543 } else {
544 $_message ||= get_commit_entry($tb)->{log};
545 }
546 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 547 $svn_path ||= $ra->{svn_path};
44320b9e
EW
548 my $r = $_revision;
549 if ($r eq 'HEAD') {
550 $r = $ra->get_latest_revnum;
551 } elsif ($r !~ /^\d+$/) {
552 die "revision argument: $r not understood by git-svn\n";
553 }
61395354
EW
554 my %ed_opts = ( r => $r,
555 log => $_message,
556 ra => $ra,
557 tree_a => $ta,
558 tree_b => $tb,
559 editor_cb => sub { print "Committed r$_[0]\n" },
560 svn_path => $svn_path );
561 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
562 print "No changes\n$ta == $tb\n";
563 }
44320b9e
EW
564}
565
3397f9df
EW
566########################### utility functions #########################
567
905f8b7d
EW
568sub rebase_cmd {
569 my @cmd = qw/rebase/;
570 push @cmd, '-v' if $_verbose;
571 push @cmd, qw/--merge/ if $_merge;
572 push @cmd, "--strategy=$_strategy" if $_strategy;
573 @cmd;
574}
575
1e889ef3
EW
576sub post_fetch_checkout {
577 return if $_no_checkout;
578 my $gs = $Git::SVN::_head or return;
579 return if verify_ref('refs/heads/master^0');
580
581 my $valid_head = verify_ref('HEAD^0');
582 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
583 return if ($valid_head || !verify_ref('HEAD^0'));
584
585 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
586 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
587 return if -f $index;
588
589 chomp(my $bare = `git config --bool --get core.bare`);
590 return if $bare eq 'true';
591 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
592 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
593 print STDERR "Checked out HEAD:\n ",
594 $gs->full_url, " r", $gs->last_rev, "\n";
595}
596
98327e58
EW
597sub complete_svn_url {
598 my ($url, $path) = @_;
599 $path =~ s#/+$##;
98327e58 600 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
601 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
602 fatal("E: '$path' is not a complete URL ",
603 "and a separate URL is not specified\n");
604 }
706587fc 605 return ($url, $path);
98327e58 606 }
706587fc 607 return ($path, '');
98327e58
EW
608}
609
9d55b41a 610sub complete_url_ls_init {
706587fc
EW
611 my ($ra, $repo_path, $switch, $pfx) = @_;
612 unless ($repo_path) {
9d55b41a
EW
613 print STDERR "W: $switch not specified\n";
614 return;
615 }
706587fc
EW
616 $repo_path =~ s#/+$##;
617 if ($repo_path =~ m#^[a-z\+]+://#) {
618 $ra = Git::SVN::Ra->new($repo_path);
619 $repo_path = '';
e7db67e6 620 } else {
706587fc 621 $repo_path =~ s#^/+##;
e7db67e6 622 unless ($ra) {
706587fc 623 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 624 "and a separate URL is not specified\n");
8164b652 625 }
e7db67e6 626 }
706587fc 627 my $url = $ra->{url};
b4d57e5e
EW
628 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
629 my $k = "svn-remote.$gs->{repo_id}.url";
630 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
631 if ($orig_url && ($orig_url ne $gs->{url})) {
632 die "$k already set: $orig_url\n",
633 "wanted to set to: $gs->{url}\n";
88cf4107 634 }
b4d57e5e
EW
635 command_oneline('config', $k, $gs->{url}) unless $orig_url;
636 my $remote_path = "$ra->{svn_path}/$repo_path/*";
637 $remote_path =~ s#/+#/#g;
638 $remote_path =~ s#^/##g;
639 my ($n) = ($switch =~ /^--(\w+)/);
640 if (length $pfx && $pfx !~ m#/$#) {
641 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 642 }
b4d57e5e
EW
643 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
644 "$remote_path:refs/remotes/$pfx*");
9d55b41a
EW
645}
646
aef4e921
EW
647sub verify_ref {
648 my ($ref) = @_;
2c5c1d53
EW
649 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
650 { STDERR => 0 }); };
aef4e921
EW
651}
652
a5e0cedc 653sub get_tree_from_treeish {
cf52b8f0 654 my ($treeish) = @_;
44320b9e 655 # $treeish can be a symbolic ref, too:
aef4e921 656 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
657 my $expected;
658 while ($type eq 'tag') {
aef4e921 659 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
660 }
661 if ($type eq 'commit') {
aef4e921
EW
662 $expected = (grep /^tree /, command(qw/cat-file commit/,
663 $treeish))[0];
44320b9e 664 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
665 die "Unable to get tree from $treeish\n" unless $expected;
666 } elsif ($type eq 'tree') {
667 $expected = $treeish;
668 } else {
669 die "$treeish is a $type, expected tree, tag or commit\n";
670 }
a5e0cedc
EW
671 return $expected;
672}
673
44320b9e
EW
674sub get_commit_entry {
675 my ($treeish) = shift;
676 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
677 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
678 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
679 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 680
44320b9e 681 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 682 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 683 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 684 $type, $treeish);
3397f9df
EW
685 my $in_msg = 0;
686 while (<$msg_fh>) {
687 if (!$in_msg) {
688 $in_msg = 1 if (/^\s*$/);
df746c5a 689 } elsif (/^git-svn-id: /) {
44320b9e
EW
690 # skip this for now, we regenerate the
691 # correct one on re-fetch anyways
692 # TODO: set *:merge properties or like...
3397f9df 693 } else {
44320b9e 694 print $log_fh $_ or croak $!;
3397f9df
EW
695 }
696 }
aef4e921 697 command_close_pipe($msg_fh, $ctx);
3397f9df 698 }
44320b9e 699 close $log_fh or croak $!;
3397f9df
EW
700
701 if ($_edit || ($type eq 'tree')) {
702 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
703 # TODO: strip out spaces, comments, like git-commit.sh
704 system($editor, $commit_editmsg);
3397f9df 705 }
44320b9e
EW
706 rename $commit_editmsg, $commit_msg or croak $!;
707 open $log_fh, '<', $commit_msg or croak $!;
708 { local $/; chomp($log_entry{log} = <$log_fh>); }
709 close $log_fh or croak $!;
710 unlink $commit_msg;
711 \%log_entry;
a5e0cedc
EW
712}
713
3397f9df
EW
714sub s_to_file {
715 my ($str, $file, $mode) = @_;
716 open my $fd,'>',$file or croak $!;
717 print $fd $str,"\n" or croak $!;
718 close $fd or croak $!;
719 chmod ($mode &~ umask, $file) if (defined $mode);
720}
721
722sub file_to_s {
723 my $file = shift;
724 open my $fd,'<',$file or croak "$!: file: $file\n";
725 local $/;
726 my $ret = <$fd>;
727 close $fd or croak $!;
728 $ret =~ s/\s*$//s;
729 return $ret;
730}
731
eeb0abe0
EW
732# '<svn username> = real-name <email address>' mapping based on git-svnimport:
733sub load_authors {
734 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 735 my $log = $cmd eq 'log';
eeb0abe0
EW
736 while (<$authors>) {
737 chomp;
8815788e 738 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 739 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
740 if ($log) {
741 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
742 } else {
743 $users{$user} = [$name, $email];
744 }
79bb8d88
EW
745 }
746 close $authors or croak $!;
747}
748
e0d10e1c 749# convert GetOpt::Long specs for use by git-config
b8c92cad 750sub read_repo_config {
706587fc 751 return unless -d $ENV{GIT_DIR};
b8c92cad 752 my $opts = shift;
97ae0911 753 my @config_only;
b8c92cad 754 foreach my $o (keys %$opts) {
97ae0911
EW
755 # if we have mixedCase and a long option-only, then
756 # it's a config-only variable that we don't need for
757 # the command-line.
758 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 759 my $v = $opts->{$o};
97ae0911 760 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 761 $key =~ s/-//g;
e0d10e1c 762 my $arg = 'git-config';
b8c92cad
EW
763 $arg .= ' --int' if ($o =~ /[:=]i$/);
764 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
765 if (ref $v eq 'ARRAY') {
766 chomp(my @tmp = `$arg --get-all svn.$key`);
767 @$v = @tmp if @tmp;
768 } else {
769 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 770 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
771 $$v = $tmp;
772 }
773 }
774 }
97ae0911 775 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
776}
777
79bb8d88 778sub extract_metadata {
c1927a85 779 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
780 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
781 \s([a-f\d\-]+)$/x);
e70dc780 782 if (!defined $rev || !$uuid || !$url) {
79bb8d88 783 # some of the original repositories I made had
82e5a82f 784 # identifiers like this:
79bb8d88
EW
785 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
786 }
787 return ($url, $rev, $uuid);
788}
789
c1927a85
EW
790sub cmt_metadata {
791 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 792 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
793}
794
905f8b7d
EW
795sub working_head_info {
796 my ($head, $refs) = @_;
905f8b7d 797 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
b03c7a63
AR
798 while (my $hash = <$fh>) {
799 chomp($hash);
800 my ($url, $rev, $uuid) = cmt_metadata($hash);
13c823fb
EW
801 if (defined $url && defined $rev) {
802 if (my $gs = Git::SVN->find_by_url($url)) {
803 my $c = $gs->rev_db_get($rev);
b03c7a63 804 if ($c && $c eq $hash) {
13c823fb
EW
805 close $fh; # break the pipe
806 return ($url, $rev, $uuid, $gs);
807 }
808 }
809 }
b03c7a63 810 unshift @$refs, $hash if $refs;
905f8b7d 811 }
13c823fb
EW
812 command_close_pipe($fh, $ctx);
813 (undef, undef, undef, undef);
905f8b7d
EW
814}
815
9b981fc6
EW
816package Git::SVN;
817use strict;
818use warnings;
ecc712dd 819use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 820 $_repack $_repack_flags $_use_svm_props $_head
befc9adc 821 $_use_svnsync_props $no_reuse_existing/;
9b981fc6
EW
822use Carp qw/croak/;
823use File::Path qw/mkpath/;
373274f9 824use File::Copy qw/copy/;
9b981fc6
EW
825use IPC::Open3;
826
ecc712dd 827my $_repack_nr;
9b981fc6
EW
828# properties that we do not log:
829my %SKIP_PROP;
830BEGIN {
831 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
832 svn:special svn:executable
833 svn:entry:committed-rev
834 svn:entry:last-author
835 svn:entry:uuid
836 svn:entry:committed-date/;
91b03282
EW
837
838 # some options are read globally, but can be overridden locally
839 # per [svn-remote "..."] section. Command-line options will *NOT*
840 # override options set in an [svn-remote "..."] section
841 my $e;
62e349d2
EW
842 foreach (qw/follow_parent no_metadata use_svm_props
843 use_svnsync_props/) {
91b03282
EW
844 my $key = $_;
845 $key =~ tr/_//d;
846 $e .= "sub $_ {
847 my (\$self) = \@_;
848 return \$self->{-$_} if exists \$self->{-$_};
849 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
850 eval { command_oneline(qw/config --get/, \$k) };
851 if (\$@) {
852 \$self->{-$_} = \$Git::SVN::_$_;
853 } else {
854 my \$v = command_oneline(qw/config --bool/,\$k);
855 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
856 }
857 return \$self->{-$_} }\n";
858 }
859 $e .= "1;\n";
860 eval $e or die $@;
9b981fc6
EW
861}
862
373274f9
EW
863my %LOCKFILES;
864END { unlink keys %LOCKFILES if %LOCKFILES }
865
4bb9ed04
EW
866sub resolve_local_globs {
867 my ($url, $fetch, $glob_spec) = @_;
868 return unless defined $glob_spec;
869 my $ref = $glob_spec->{ref};
870 my $path = $glob_spec->{path};
871 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
872 next unless m#^refs/remotes/$ref->{regex}$#;
873 my $p = $1;
874 my $pathname = $path->full_path($p);
875 my $refname = $ref->full_path($p);
876 if (my $existing = $fetch->{$pathname}) {
877 if ($existing ne $refname) {
878 die "Refspec conflict:\n",
879 "existing: refs/remotes/$existing\n",
880 " globbed: refs/remotes/$refname\n";
881 }
882 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 883 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
884 "refs/remotes/$refname: '$url' not found in '$u'\n";
885 if ($pathname ne $u) {
886 warn "W: Refspec glob conflict ",
887 "(ref: refs/remotes/$refname):\n",
888 "expected path: $pathname\n",
889 " real path: $u\n",
890 "Continuing ahead with $u\n";
891 next;
892 }
893 } else {
4bb9ed04
EW
894 $fetch->{$pathname} = $refname;
895 }
896 }
897}
898
e98671e5
EW
899sub parse_revision_argument {
900 my ($base, $head) = @_;
901 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
902 return ($base, $head);
903 }
904 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
905 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
906 return ($head, $head) if ($::_revision eq 'HEAD');
907 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
908 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
909 die "revision argument: $::_revision not understood by git-svn\n";
910}
911
0af9c9f9 912sub fetch_all {
4bb9ed04 913 my ($repo_id, $remotes) = @_;
905f8b7d
EW
914 if (ref $repo_id) {
915 my $gs = $repo_id;
916 $repo_id = undef;
917 $repo_id = $gs->{repo_id};
918 }
919 $remotes ||= read_all_remotes();
7447b4bc
EW
920 my $remote = $remotes->{$repo_id} or
921 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 922 my $fetch = $remote->{fetch};
7447b4bc 923 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 924 my (@gs, @globs);
0af9c9f9 925 my $ra = Git::SVN::Ra->new($url);
26a62d57 926 my $uuid = $ra->get_uuid;
0af9c9f9 927 my $head = $ra->get_latest_revnum;
28710f74 928 my $base = defined $fetch ? $head : 0;
e518192f
EW
929
930 # read the max revs for wildcard expansion (branches/*, tags/*)
931 foreach my $t (qw/branches tags/) {
932 defined $remote->{$t} or next;
933 push @globs, $remote->{$t};
93f2689c
EW
934 my $max_rev = eval { tmp_config(qw/--int --get/,
935 "svn-remote.$repo_id.${t}-maxRev") };
936 if (defined $max_rev && ($max_rev < $base)) {
937 $base = $max_rev;
d6d3346b
EW
938 } elsif (!defined $max_rev) {
939 $base = 0;
e518192f
EW
940 }
941 }
942
db03cd24
EW
943 if ($fetch) {
944 foreach my $p (sort keys %$fetch) {
945 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
946 my $lr = $gs->rev_db_max;
947 if (defined $lr) {
948 $base = $lr if ($lr < $base);
949 }
950 push @gs, $gs;
0af9c9f9 951 }
0af9c9f9 952 }
e98671e5
EW
953
954 ($base, $head) = parse_revision_argument($base, $head);
e518192f 955 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
956}
957
47e39c55
EW
958sub read_all_remotes {
959 my $r = {};
8b8fc068 960 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55
EW
961 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
962 $r->{$1}->{fetch}->{$2} = $3;
963 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
964 $r->{$1}->{url} = $2;
4bb9ed04
EW
965 } elsif (m!^(.+)\.(branches|tags)=
966 (.*):refs/remotes/(.+)\s*$/!x) {
967 my ($p, $g) = ($3, $4);
968 my $rs = $r->{$1}->{$2} = {
e518192f 969 t => $2,
93f2689c 970 remote => $1,
4bb9ed04
EW
971 path => Git::SVN::GlobSpec->new($p),
972 ref => Git::SVN::GlobSpec->new($g) };
973 if (length($rs->{ref}->{right}) != 0) {
974 die "The '*' glob character must be the last ",
975 "character of '$g'\n";
976 }
47e39c55
EW
977 }
978 }
979 $r;
980}
981
ecc712dd
EW
982sub init_vars {
983 if (defined $_repack) {
984 $_repack = 1000 if ($_repack <= 0);
985 $_repack_nr = $_repack;
986 $_repack_flags ||= '-d';
987 }
988}
989
b805b44a 990sub verify_remotes_sanity {
536c4b09 991 return unless -d $ENV{GIT_DIR};
b805b44a
EW
992 my %seen;
993 foreach (command(qw/config -l/)) {
994 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
995 if ($seen{$1}) {
996 die "Remote ref refs/remote/$1 is tracked by",
997 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
998 "Please resolve this ambiguity in ",
999 "your git configuration file before ",
1000 "continuing\n";
1001 }
1002 $seen{$1} = $_;
1003 }
1004 }
1005}
1006
47e39c55 1007# we allow more chars than remotes2config.sh...
706587fc
EW
1008sub sanitize_remote_name {
1009 my ($name) = @_;
47e39c55 1010 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
1011 $name;
1012}
1013
e6434f87
EW
1014sub find_existing_remote {
1015 my ($url, $remotes) = @_;
befc9adc 1016 return undef if $no_reuse_existing;
e6434f87
EW
1017 my $existing;
1018 foreach my $repo_id (keys %$remotes) {
1019 my $u = $remotes->{$repo_id}->{url} or next;
1020 next if $u ne $url;
1021 $existing = $repo_id;
1022 last;
1023 }
1024 $existing;
1025}
b805b44a 1026
e6434f87 1027sub init_remote_config {
d8115c51 1028 my ($self, $url, $no_write) = @_;
e6434f87
EW
1029 $url =~ s!/+$!!; # strip trailing slash
1030 my $r = read_all_remotes();
1031 my $existing = find_existing_remote($url, $r);
1032 if ($existing) {
e518192f
EW
1033 unless ($no_write) {
1034 print STDERR "Using existing ",
1035 "[svn-remote \"$existing\"]\n";
1036 }
e6434f87
EW
1037 $self->{repo_id} = $existing;
1038 } else {
1039 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1040 $existing = find_existing_remote($min_url, $r);
1041 if ($existing) {
e518192f
EW
1042 unless ($no_write) {
1043 print STDERR "Using existing ",
1044 "[svn-remote \"$existing\"]\n";
1045 }
e6434f87
EW
1046 $self->{repo_id} = $existing;
1047 }
1048 if ($min_url ne $url) {
e518192f
EW
1049 unless ($no_write) {
1050 print STDERR "Using higher level of URL: ",
1051 "$url => $min_url\n";
1052 }
e6434f87
EW
1053 my $old_path = $self->{path};
1054 $self->{path} = $url;
4e9f6cc7 1055 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1056 if (length $old_path) {
1057 $self->{path} .= "/$old_path";
1058 }
1059 $url = $min_url;
1060 }
1061 }
1062 my $orig_url;
1063 if (!$existing) {
b805b44a 1064 # verify that we aren't overwriting anything:
e6434f87 1065 $orig_url = eval {
706587fc 1066 command_oneline('config', '--get',
e6434f87 1067 "svn-remote.$self->{repo_id}.url")
706587fc 1068 };
b805b44a 1069 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1070 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1071 "$orig_url\nwanted to set to: $url\n";
1072 }
9b981fc6 1073 }
e6434f87
EW
1074 my ($xrepo_id, $xpath) = find_ref($self->refname);
1075 if (defined $xpath) {
1076 die "svn-remote.$xrepo_id.fetch already set to track ",
1077 "$xpath:refs/remotes/", $self->refname, "\n";
1078 }
d8115c51
EW
1079 unless ($no_write) {
1080 command_noisy('config',
1081 "svn-remote.$self->{repo_id}.url", $url);
1082 command_noisy('config', '--add',
1083 "svn-remote.$self->{repo_id}.fetch",
1084 "$self->{path}:".$self->refname);
1085 }
9b981fc6 1086 $self->{url} = $url;
e6434f87
EW
1087}
1088
a8ae2623
EW
1089sub find_by_url { # repos_root and, path are optional
1090 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1091
1a97a506 1092 return undef unless defined $full_url;
56973d20
AR
1093 remove_username($full_url);
1094 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1095 my $remotes = read_all_remotes();
1096 if (defined $full_url && defined $repos_root && !defined $path) {
1097 $path = $full_url;
1098 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1099 }
1100 foreach my $repo_id (keys %$remotes) {
1101 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1102 remove_username($u);
a8ae2623
EW
1103 next if defined $repos_root && $repos_root ne $u;
1104
1105 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1106 foreach (qw/branches tags/) {
1107 resolve_local_globs($u, $fetch,
1108 $remotes->{$repo_id}->{$_});
1109 }
1110 my $p = $path;
1111 unless (defined $p) {
1112 $p = $full_url;
1113 $p =~ s#^\Q$u\E(?:/|$)## or next;
1114 }
1115 foreach my $f (keys %$fetch) {
1116 next if $f ne $p;
1117 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1118 }
1119 }
1120 undef;
1121}
1122
e6434f87 1123sub init {
d8115c51 1124 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1125 my $self = _new($class, $repo_id, $ref_id, $path);
1126 if (defined $url) {
d8115c51 1127 $self->init_remote_config($url, $no_write);
e6434f87 1128 }
9b981fc6
EW
1129 $self;
1130}
1131
706587fc
EW
1132sub find_ref {
1133 my ($ref_id) = @_;
1134 foreach (command(qw/config -l/)) {
1135 next unless m!^svn-remote\.(.+)\.fetch=
1136 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1137 my ($repo_id, $path, $ref) = ($1, $2, $3);
1138 if ($ref eq $ref_id) {
1139 $path = '' if ($path =~ m#^\./?#);
1140 return ($repo_id, $path);
1141 }
1142 }
1143 (undef, undef, undef);
1144}
1145
9b981fc6 1146sub new {
706587fc
EW
1147 my ($class, $ref_id, $repo_id, $path) = @_;
1148 if (defined $ref_id && !defined $repo_id && !defined $path) {
1149 ($repo_id, $path) = find_ref($ref_id);
1150 if (!defined $repo_id) {
1151 die "Could not find a \"svn-remote.*.fetch\" key ",
1152 "in the repository configuration matching: ",
1153 "refs/remotes/$ref_id\n";
1154 }
1155 }
1156 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1157 if (!defined $self->{path} || !length $self->{path}) {
1158 my $fetch = command_oneline('config', '--get',
1159 "svn-remote.$repo_id.fetch",
1160 ":refs/remotes/$ref_id\$") or
1161 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1162 "\":refs/remotes/$ref_id\$\" in config\n";
1163 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1164 }
706587fc
EW
1165 $self->{url} = command_oneline('config', '--get',
1166 "svn-remote.$repo_id.url") or
1167 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1168 $self->rebuild;
9b981fc6
EW
1169 $self;
1170}
1171
706587fc 1172sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6 1173
26a62d57
EW
1174sub svm_uuid {
1175 my ($self) = @_;
1176 return $self->{svm}->{uuid} if $self->svm;
1177 $self->ra;
1178 unless ($self->{svm}) {
1179 die "SVM UUID not cached, and reading remotely failed\n";
1180 }
1181 $self->{svm}->{uuid};
1182}
8a49ee97 1183
26a62d57
EW
1184sub svm {
1185 my ($self) = @_;
1186 return $self->{svm} if $self->{svm};
1187 my $svm;
8a49ee97
EW
1188 # see if we have it in our config, first:
1189 eval {
26a62d57
EW
1190 my $section = "svn-remote.$self->{repo_id}";
1191 $svm = {
93f2689c
EW
1192 source => tmp_config('--get', "$section.svm-source"),
1193 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1194 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1195 }
1196 };
befc9adc
EW
1197 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1198 $self->{svm} = $svm;
1199 }
26a62d57
EW
1200 $self->{svm};
1201}
1202
1203sub _set_svm_vars {
1204 my ($self, $ra) = @_;
db03cd24
EW
1205 return $ra if $self->svm;
1206
1207 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1208 "(svm:source, svm:uuid) ",
db03cd24
EW
1209 "from the following URLs:\n" );
1210 sub read_svm_props {
befc9adc
EW
1211 my ($self, $ra, $path, $r) = @_;
1212 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1213 my $src = $props->{'svm:source'};
db03cd24 1214 my $uuid = $props->{'svm:uuid'};
befc9adc 1215 return undef if (!$src || !$uuid);
26a62d57 1216
befc9adc 1217 chomp($src, $uuid);
26a62d57 1218
db03cd24
EW
1219 $uuid =~ m{^[0-9a-f\-]{30,}$}
1220 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1221
1222 # the '!' is used to mark the repos_root!/relative/path
1223 $src =~ s{/?!/?}{/};
db03cd24 1224 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1225 # username is of no interest
8a49ee97 1226 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1227
befc9adc
EW
1228 my $replace = $ra->{url};
1229 $replace .= "/$path" if length $path;
1230
db03cd24 1231 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1232 tmp_config("$section.svm-source", $src);
1233 tmp_config("$section.svm-replace", $replace);
1234 tmp_config("$section.svm-uuid", $uuid);
1235 $self->{svm} = {
1236 source => $src,
1237 uuid => $uuid,
1238 replace => $replace
1239 };
db03cd24
EW
1240 }
1241
1242 my $r = $ra->get_latest_revnum;
1243 my $path = $self->{path};
befc9adc 1244 my %tried;
db03cd24 1245 while (length $path) {
befc9adc
EW
1246 unless ($tried{"$self->{url}/$path"}) {
1247 return $ra if $self->read_svm_props($ra, $path, $r);
1248 $tried{"$self->{url}/$path"} = 1;
db03cd24 1249 }
befc9adc 1250 $path =~ s#/?[^/]+$##;
8a49ee97 1251 }
befc9adc
EW
1252 die "Path: '$path' should be ''\n" if $path ne '';
1253 return $ra if $self->read_svm_props($ra, $path, $r);
1254 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1255
1256 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1257 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1258 }
1259
1260 # nope, make sure we're connected to the repository root:
1261 my $ok;
1262 my @tried_b;
1263 $path = $ra->{svn_path};
db03cd24
EW
1264 $ra = Git::SVN::Ra->new($ra->{repos_root});
1265 while (length $path) {
befc9adc
EW
1266 unless ($tried{"$ra->{url}/$path"}) {
1267 $ok = $self->read_svm_props($ra, $path, $r);
1268 last if $ok;
1269 $tried{"$ra->{url}/$path"} = 1;
1270 }
1271 $path =~ s#/?[^/]+$##;
db03cd24 1272 }
befc9adc
EW
1273 die "Path: '$path' should be ''\n" if $path ne '';
1274 $ok ||= $self->read_svm_props($ra, $path, $r);
1275 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1276 if (!$ok) {
befc9adc 1277 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1278 }
1279 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1280}
1281
62e349d2
EW
1282sub svnsync {
1283 my ($self) = @_;
1284 return $self->{svnsync} if $self->{svnsync};
1285
1286 if ($self->no_metadata) {
1287 die "Can't have both 'noMetadata' and ",
1288 "'useSvnsyncProps' options set!\n";
1289 }
1290 if ($self->rewrite_root) {
1291 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1292 "options set!\n";
1293 }
1294
1295 my $svnsync;
1296 # see if we have it in our config, first:
1297 eval {
1298 my $section = "svn-remote.$self->{repo_id}";
1299 $svnsync = {
1300 url => tmp_config('--get', "$section.svnsync-url"),
1301 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1302 }
1303 };
1304 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1305 return $self->{svnsync} = $svnsync;
1306 }
1307
1308 my $err = "useSvnsyncProps set, but failed to read " .
1309 "svnsync property: svn:sync-from-";
1310 my $rp = $self->ra->rev_proplist(0);
1311
1312 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1313 $url =~ m{^[a-z\+]+://} or
1314 die "doesn't look right - svn:sync-from-url is '$url'\n";
1315
1316 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1317 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1318 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1319
1320 my $section = "svn-remote.$self->{repo_id}";
1321 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1322 tmp_config('--add', "$section.svnsync-url", $url);
1323 return $self->{svnsync} = { url => $url, uuid => $uuid };
1324}
1325
26a62d57
EW
1326# this allows us to memoize our SVN::Ra UUID locally and avoid a
1327# remote lookup (useful for 'git svn log').
1328sub ra_uuid {
1329 my ($self) = @_;
1330 unless ($self->{ra_uuid}) {
1331 my $key = "svn-remote.$self->{repo_id}.uuid";
1332 my $uuid = eval { tmp_config('--get', $key) };
1333 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1334 $self->{ra_uuid} = $uuid;
1335 } else {
1336 die "ra_uuid called without URL\n" unless $self->{url};
1337 $self->{ra_uuid} = $self->ra->get_uuid;
1338 tmp_config('--add', $key, $self->{ra_uuid});
1339 }
1340 }
1341 $self->{ra_uuid};
1342}
1343
9b981fc6
EW
1344sub ra {
1345 my ($self) = shift;
8a49ee97 1346 my $ra = Git::SVN::Ra->new($self->{url});
91b03282
EW
1347 if ($self->use_svm_props && !$self->{svm}) {
1348 if ($self->no_metadata) {
97ae0911
EW
1349 die "Can't have both 'noMetadata' and ",
1350 "'useSvmProps' options set!\n";
62e349d2
EW
1351 } elsif ($self->use_svnsync_props) {
1352 die "Can't have both 'useSvnsyncProps' and ",
1353 "'useSvmProps' options set!\n";
91b03282 1354 }
26a62d57 1355 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1356 $self->{-want_revprops} = 1;
1357 }
1358 $ra;
9b981fc6
EW
1359}
1360
15710b6f
EW
1361sub rel_path {
1362 my ($self) = @_;
1363 my $repos_root = $self->ra->{repos_root};
1364 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
1365 my $url = $self->{url} .
1366 (length $self->{path} ? "/$self->{path}" : $self->{path});
1367 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1368 $url;
15710b6f
EW
1369}
1370
9b981fc6
EW
1371sub traverse_ignore {
1372 my ($self, $fh, $path, $r) = @_;
1373 $path =~ s#^/+##g;
5d3b7cd5
EW
1374 my $ra = $self->ra;
1375 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
9b981fc6 1376 my $p = $path;
102a0a2d 1377 $p =~ s#^\Q$self->{path}\E(/|$)##;
9b981fc6
EW
1378 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1379 if (my $s = $props->{'svn:ignore'}) {
1380 $s =~ s/[\r\n]+/\n/g;
1381 chomp $s;
1382 if (length $p == 0) {
1383 $s =~ s#\n#\n/$p#g;
1384 print $fh "/$s\n";
1385 } else {
1386 $s =~ s#\n#\n/$p/#g;
1387 print $fh "/$p/$s\n";
1388 }
1389 }
1390 foreach (sort keys %$dirent) {
1391 next if $dirent->{$_}->kind != $SVN::Node::dir;
1392 $self->traverse_ignore($fh, "$path/$_", $r);
1393 }
1394}
1395
3ebe8df7
EW
1396sub last_rev { ($_[0]->last_rev_commit)[0] }
1397sub last_commit { ($_[0]->last_rev_commit)[1] }
1398
9b981fc6
EW
1399# returns the newest SVN revision number and newest commit SHA1
1400sub last_rev_commit {
1401 my ($self) = @_;
1402 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1403 return ($self->{last_rev}, $self->{last_commit});
1404 }
d2866f9e 1405 my $c = ::verify_ref($self->refname.'^0');
91b03282 1406 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1407 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1408 if (defined $rev) {
1409 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1410 return ($rev, $c);
1411 }
1412 }
26a62d57
EW
1413 my $db_path = $self->db_path;
1414 unless (-e $db_path) {
1415 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1416 return (undef, undef);
1417 }
9b981fc6
EW
1418 my $offset = -41; # from tail
1419 my $rl;
26a62d57 1420 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
ce4b4af7
EW
1421 sysseek($fh, $offset, 2); # don't care for errors
1422 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6 1423 chomp $rl;
ce4b4af7 1424 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
9b981fc6 1425 $offset -= 41;
ce4b4af7
EW
1426 sysseek($fh, $offset, 2); # don't care for errors
1427 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6
EW
1428 chomp $rl;
1429 }
91b03282 1430 if ($c && $c ne $rl) {
26a62d57 1431 die "$db_path and ", $self->refname,
9c93fee5
EW
1432 " inconsistent!:\n$c != $rl\n";
1433 }
ce4b4af7 1434 my $rev = sysseek($fh, 0, 1) or croak $!;
9b981fc6
EW
1435 $rev = ($rev - 41) / 41;
1436 close $fh or croak $!;
1437 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1438 return ($rev, $c);
1439}
1440
3ebe8df7
EW
1441sub get_fetch_range {
1442 my ($self, $min, $max) = @_;
1443 $max ||= $self->ra->get_latest_revnum;
9c93fee5 1444 $min ||= $self->rev_db_max;
3ebe8df7 1445 (++$min, $max);
9b981fc6
EW
1446}
1447
8a49ee97 1448sub tmp_config {
93f2689c 1449 my (@args) = @_;
b7e5348c
EW
1450 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1451 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1452 if (-e $old_def_config && ! -e $config) {
1453 rename $old_def_config, $config or
1454 die "Failed rename $old_def_config => $config: $!\n";
1455 }
8a49ee97 1456 my $old_config = $ENV{GIT_CONFIG};
93f2689c 1457 $ENV{GIT_CONFIG} = $config;
8a49ee97 1458 $@ = undef;
b4d57e5e
EW
1459 my @ret = eval {
1460 unless (-f $config) {
1461 mkfile($config);
1462 open my $fh, '>', $config or
1463 die "Can't open $config: $!\n";
1464 print $fh "; This file is used internally by ",
1465 "git-svn\n" or die
1466 "Couldn't write to $config: $!\n";
1467 print $fh "; You should not have to edit it\n" or
1468 die "Couldn't write to $config: $!\n";
1469 close $fh or die "Couldn't close $config: $!\n";
1470 }
1471 command('config', @args);
1472 };
8a49ee97
EW
1473 my $err = $@;
1474 if (defined $old_config) {
1475 $ENV{GIT_CONFIG} = $old_config;
1476 } else {
1477 delete $ENV{GIT_CONFIG};
1478 }
1479 die $err if $err;
1480 wantarray ? @ret : $ret[0];
1481}
1482
9b981fc6
EW
1483sub tmp_index_do {
1484 my ($self, $sub) = @_;
1485 my $old_index = $ENV{GIT_INDEX_FILE};
1486 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 1487 $@ = undef;
b4d57e5e
EW
1488 my @ret = eval {
1489 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1490 mkpath([$dir]) unless -d $dir;
1491 &$sub;
1492 };
8a49ee97
EW
1493 my $err = $@;
1494 if (defined $old_index) {
9b981fc6
EW
1495 $ENV{GIT_INDEX_FILE} = $old_index;
1496 } else {
1497 delete $ENV{GIT_INDEX_FILE};
1498 }
8a49ee97 1499 die $err if $err;
9b981fc6
EW
1500 wantarray ? @ret : $ret[0];
1501}
1502
1503sub assert_index_clean {
1504 my ($self, $treeish) = @_;
1505
1506 $self->tmp_index_do(sub {
1507 command_noisy('read-tree', $treeish) unless -e $self->{index};
1508 my $x = command_oneline('write-tree');
1509 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1510 /^tree ($::sha1)/mo);
e8d120bd
EW
1511 return if $y eq $x;
1512
1513 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1514 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1515 command_noisy('read-tree', $treeish);
9b981fc6
EW
1516 $x = command_oneline('write-tree');
1517 if ($y ne $x) {
1518 ::fatal "trees ($treeish) $y != $x\n",
1519 "Something is seriously wrong...\n";
1520 }
1521 });
1522}
1523
1524sub get_commit_parents {
0af9c9f9 1525 my ($self, $log_entry) = @_;
9b981fc6 1526 my (%seen, @ret, @tmp);
0af9c9f9
EW
1527 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1528 if (my $ip = $self->{inject_parents}) {
1529 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1530 push @tmp, $commit;
9b981fc6
EW
1531 }
1532 }
d2866f9e 1533 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
1534 push @tmp, $cur;
1535 }
44320b9e 1536 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
1537 while (my $p = shift @tmp) {
1538 next if $seen{$p};
1539 $seen{$p} = 1;
1540 push @ret, $p;
1541 # MAXPARENT is defined to 16 in commit-tree.c:
1542 last if @ret >= 16;
1543 }
1544 if (@tmp) {
44320b9e 1545 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
1546 join("\n\t", @tmp), "\n";
1547 }
1548 @ret;
1549}
1550
aea736cc
EW
1551sub rewrite_root {
1552 my ($self) = @_;
1553 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1554 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1555 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1556 if ($rwr) {
1557 $rwr =~ s#/+$##;
1558 if ($rwr !~ m#^[a-z\+]+://#) {
1559 die "$rwr is not a valid URL (key: $k)\n";
1560 }
1561 }
1562 $self->{-rewrite_root} = $rwr;
1563}
1564
1565sub metadata_url {
1566 my ($self) = @_;
1567 ($self->rewrite_root || $self->{url}) .
1568 (length $self->{path} ? '/' . $self->{path} : '');
1569}
1570
706587fc 1571sub full_url {
9b981fc6 1572 my ($self) = @_;
5d3b7cd5 1573 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
1574}
1575
1576sub do_git_commit {
0af9c9f9 1577 my ($self, $log_entry) = @_;
8a603774
EW
1578 my $lr = $self->last_rev;
1579 if (defined $lr && $lr >= $log_entry->{revision}) {
1580 die "Last fetched revision of ", $self->refname,
1581 " was r$lr, but we are about to fetch: ",
1582 "r$log_entry->{revision}!\n";
1583 }
44320b9e
EW
1584 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1585 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
1586 "Why are we refetching it?\n";
1587 }
db03cd24
EW
1588 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1589 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1590 $log_entry->{email};
44320b9e 1591 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 1592
44320b9e 1593 my $tree = $log_entry->{tree};
9b981fc6
EW
1594 if (!defined $tree) {
1595 $tree = $self->tmp_index_do(sub {
1596 command_oneline('write-tree') });
1597 }
1598 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1599
1600 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1601 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1602 push @exec, '-p', $_;
1603 }
1604 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1605 or croak $!;
44320b9e 1606 print $msg_fh $log_entry->{log} or croak $!;
91b03282 1607 unless ($self->no_metadata) {
8a49ee97
EW
1608 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1609 or croak $!;
9760adcc 1610 }
9b981fc6
EW
1611 $msg_fh->flush == 0 or croak $!;
1612 close $msg_fh or croak $!;
1613 chomp(my $commit = do { local $/; <$out_fh> });
1614 close $out_fh or croak $!;
1615 waitpid $pid, 0;
1616 croak $? if $?;
1617 if ($commit !~ /^$::sha1$/o) {
1618 die "Failed to commit, invalid sha1: $commit\n";
1619 }
1620
373274f9 1621 $self->rev_db_set($log_entry->{revision}, $commit, 1);
9b981fc6 1622
44320b9e 1623 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1624 $self->{last_commit} = $commit;
8a49ee97
EW
1625 print "r$log_entry->{revision}";
1626 if (defined $log_entry->{svm_revision}) {
1627 print " (\@$log_entry->{svm_revision})";
26a62d57
EW
1628 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1629 0, $self->svm_uuid);
8a49ee97
EW
1630 }
1631 print " = $commit ($self->{ref_id})\n";
ecc712dd
EW
1632 if (defined $_repack && (--$_repack_nr == 0)) {
1633 $_repack_nr = $_repack;
1634 # repack doesn't use any arguments with spaces in them, does it?
1635 print "Running git repack $_repack_flags ...\n";
1636 command_noisy('repack', split(/\s+/, $_repack_flags));
1637 print "Done repacking\n";
1638 }
9b981fc6
EW
1639 return $commit;
1640}
1641
fbcc1737
EW
1642sub match_paths {
1643 my ($self, $paths, $r) = @_;
4e9f6cc7 1644 return 1 if $self->{path} eq '';
d542aedb
EW
1645 if (my $path = $paths->{"/$self->{path}"}) {
1646 return ($path->{action} eq 'D') ? 0 : 1;
1647 }
4e9f6cc7 1648 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
1649 if (grep /$self->{path_regex}/, keys %$paths) {
1650 return 1;
1651 }
1652 my $c = '';
1653 foreach (split m#/#, $self->{path}) {
1654 $c .= "/$_";
74a81227
EW
1655 next unless ($paths->{$c} &&
1656 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
1657 if ($self->ra->check_path($self->{path}, $r) ==
1658 $SVN::Node::dir) {
fbcc1737
EW
1659 return 1;
1660 }
1661 }
1662 return 0;
1663}
1664
15710b6f
EW
1665sub find_parent_branch {
1666 my ($self, $paths, $rev) = @_;
91b03282 1667 return undef unless $self->follow_parent;
e5a0b240 1668 unless (defined $paths) {
c7eba716
EW
1669 my $err_handler = $SVN::Error::handler;
1670 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1671 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1672 $paths =
1673 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1674 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1675 }
1676 return undef unless defined $paths;
15710b6f
EW
1677
1678 # look for a parent from another branch:
7f578c55
EW
1679 my @b_path_components = split m#/#, $self->rel_path;
1680 my @a_path_components;
1681 my $i;
1682 while (@b_path_components) {
1683 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 1684 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
1685 unshift(@a_path_components, pop(@b_path_components));
1686 }
74a81227
EW
1687 return undef unless defined $i && defined $i->{copyfrom_path};
1688 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
1689 if (@a_path_components) {
1690 print STDERR "branch_from: $branch_from => ";
1691 $branch_from .= '/'.join('/', @a_path_components);
1692 print STDERR $branch_from, "\n";
1693 }
3ebe8df7 1694 my $r = $i->{copyfrom_rev};
15710b6f
EW
1695 my $repos_root = $self->ra->{repos_root};
1696 my $url = $self->ra->{url};
1697 my $new_url = $repos_root . $branch_from;
1698 print STDERR "Found possible branch point: ",
1699 "$new_url => ", $self->full_url, ", $r\n";
1700 $branch_from =~ s#^/##;
a8ae2623 1701 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 1702 unless ($gs) {
ce2a0f2f
EW
1703 my $ref_id = $self->{ref_id};
1704 $ref_id =~ s/\@\d+$//;
1705 $ref_id .= "\@$r";
15710b6f
EW
1706 # just grow a tail if we're not unique enough :x
1707 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1708 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1709 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1710 }
1711 my ($r0, $parent) = $gs->find_rev_before($r, 1);
91b03282 1712 if (!defined $r0 || !defined $parent) {
d627de6b
EW
1713 my ($base, $head) = parse_revision_argument(0, $r);
1714 if ($base <= $r) {
1715 $gs->fetch($base, $r);
1716 }
15710b6f
EW
1717 ($r0, $parent) = $gs->last_rev_commit;
1718 }
ef70de96 1719 if (defined $r0 && defined $parent) {
15710b6f 1720 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
1721 my $ed;
1722 if ($self->ra->can_do_switch) {
2e5e2480 1723 $self->assert_index_clean($parent);
8b8fc068 1724 print STDERR "Following parent with do_switch\n";
15710b6f 1725 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1726 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1727 # at the moment), so we can't rely on it
1728 $self->{last_commit} = $parent;
1729 $ed = SVN::Git::Fetcher->new($self);
8a603774 1730 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1731 $self->full_url, $ed)
1732 or die "SVN connection failed somewhere...\n";
1733 } else {
8b8fc068 1734 print STDERR "Following parent with do_update\n";
15710b6f 1735 $ed = SVN::Git::Fetcher->new($self);
8a603774 1736 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1737 or die "SVN connection failed somewhere...\n";
1738 }
f7c3fc4a 1739 print STDERR "Successfully followed parent\n";
15710b6f
EW
1740 return $self->make_log_entry($rev, [$parent], $ed);
1741 }
15710b6f
EW
1742 return undef;
1743}
1744
9b981fc6 1745sub do_fetch {
706587fc 1746 my ($self, $paths, $rev) = @_;
15710b6f 1747 my $ed;
9b981fc6 1748 my ($last_rev, @parents);
b9dffd8c
EW
1749 if (my $lc = $self->last_commit) {
1750 # we can have a branch that was deleted, then re-added
1751 # under the same name but copied from another path, in
1752 # which case we'll have multiple parents (we don't
1753 # want to break the original ref, nor lose copypath info):
1754 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1755 push @{$log_entry->{parents}}, $lc;
1756 return $log_entry;
1757 }
15710b6f 1758 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1759 $last_rev = $self->{last_rev};
b9dffd8c
EW
1760 $ed->{c} = $lc;
1761 @parents = ($lc);
9b981fc6
EW
1762 } else {
1763 $last_rev = $rev;
15710b6f
EW
1764 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1765 return $log_entry;
1766 }
1767 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1768 }
8a603774 1769 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1770 die "SVN connection failed somewhere...\n";
1771 }
1772 $self->make_log_entry($rev, \@parents, $ed);
1773}
1774
97f6987a
EW
1775sub get_untracked {
1776 my ($self, $ed) = @_;
1777 my @out;
1778 my $h = $ed->{empty};
9b981fc6
EW
1779 foreach (sort keys %$h) {
1780 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1781 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1782 warn "W: $act: $_\n";
1783 }
1784 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1785 $h = $ed->{$t} or next;
9b981fc6
EW
1786 foreach my $path (sort keys %$h) {
1787 my $ppath = $path eq '' ? '.' : $path;
1788 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1789 next if $SKIP_PROP{$prop};
9b981fc6 1790 my $v = $h->{$path}->{$prop};
97f6987a
EW
1791 my $t_ppath_prop = "$t: " .
1792 uri_encode($ppath) . ' ' .
1793 uri_encode($prop);
9b981fc6 1794 if (defined $v) {
97f6987a
EW
1795 push @out, " +$t_ppath_prop " .
1796 uri_encode($v);
9b981fc6 1797 } else {
97f6987a 1798 push @out, " -$t_ppath_prop";
9b981fc6
EW
1799 }
1800 }
1801 }
1802 }
1803 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1804 $h = $ed->{$t} or next;
9b981fc6
EW
1805 foreach my $parent (sort keys %$h) {
1806 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1807 push @out, " $t: " .
1808 uri_encode("$parent/$path");
9b981fc6
EW
1809 warn "W: $t: $parent/$path ",
1810 "Insufficient permissions?\n";
1811 }
1812 }
1813 }
97f6987a 1814 \@out;
9b981fc6
EW
1815}
1816
1c8443b0
EW
1817sub parse_svn_date {
1818 my $date = shift || return '+0000 1970-01-01 00:00:00';
1819 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1820 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1821 croak "Unable to parse date: $date\n";
1822 "+0000 $Y-$m-$d $H:$M:$S";
1823}
1824
1825sub check_author {
1826 my ($author) = @_;
1827 if (!defined $author || length $author == 0) {
1828 $author = '(no author)';
1829 }
1830 if (defined $::_authors && ! defined $::users{$author}) {
1831 die "Author: $author not defined in $::_authors file\n";
1832 }
1833 $author;
1834}
1835
9b981fc6 1836sub make_log_entry {
97f6987a
EW
1837 my ($self, $rev, $parents, $ed) = @_;
1838 my $untracked = $self->get_untracked($ed);
1839
9b981fc6 1840 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1841 print $un "r$rev\n" or croak $!;
1842 print $un $_, "\n" foreach @$untracked;
1843 my %log_entry = ( parents => $parents || [], revision => $rev,
1844 log => '');
fbcc1737 1845
8a49ee97 1846 my $headrev;
fbcc1737 1847 my $logged = delete $self->{logged_rev_props};
8a49ee97 1848 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
1849 my $rp = $self->ra->rev_proplist($rev);
1850 foreach (sort keys %$rp) {
1851 my $v = $rp->{$_};
1852 if (/^svn:(author|date|log)$/) {
1853 $log_entry{$1} = $v;
8a49ee97
EW
1854 } elsif ($_ eq 'svm:headrev') {
1855 $headrev = $v;
fbcc1737
EW
1856 } else {
1857 print $un " rev_prop: ", uri_encode($_), ' ',
1858 uri_encode($v), "\n";
1859 }
9b981fc6 1860 }
fbcc1737
EW
1861 } else {
1862 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1863 }
1864 close $un or croak $!;
97f6987a 1865
9b981fc6 1866 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 1867 $log_entry{log} .= "\n";
db03cd24
EW
1868 my $author = $log_entry{author} = check_author($log_entry{author});
1869 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1870 : ($author, undef);
91b03282 1871 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
1872 if ($self->rewrite_root) {
1873 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1874 "options set!\n";
1875 }
8a49ee97 1876 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
1877 # we don't want "SVM: initializing mirror for junk" ...
1878 return undef if $r == 0;
1879 my $svm = $self->svm;
1880 if ($uuid ne $svm->{uuid}) {
8a49ee97 1881 die "UUID mismatch on SVM path:\n",
befc9adc 1882 "expected: $svm->{uuid}\n",
8a49ee97
EW
1883 " got: $uuid\n";
1884 }
befc9adc
EW
1885 my $full_url = $self->full_url;
1886 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1887 die "Failed to replace '$svm->{replace}' with ",
1888 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
1889 # throw away username for storing in records
1890 remove_username($full_url);
8a49ee97
EW
1891 $log_entry{metadata} = "$full_url\@$r $uuid";
1892 $log_entry{svm_revision} = $r;
db03cd24 1893 $email ||= "$author\@$uuid"
62e349d2
EW
1894 } elsif ($self->use_svnsync_props) {
1895 my $full_url = $self->svnsync->{url};
1896 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 1897 remove_username($full_url);
62e349d2
EW
1898 my $uuid = $self->svnsync->{uuid};
1899 $log_entry{metadata} = "$full_url\@$rev $uuid";
1900 $email ||= "$author\@$uuid"
8a49ee97 1901 } else {
ce118739
AR
1902 my $url = $self->metadata_url;
1903 remove_username($url);
1904 $log_entry{metadata} = "$url\@$rev " .
26a62d57 1905 $self->ra->get_uuid;
db03cd24 1906 $email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 1907 }
db03cd24
EW
1908 $log_entry{name} = $name;
1909 $log_entry{email} = $email;
9b981fc6
EW
1910 \%log_entry;
1911}
1912
1913sub fetch {
3ebe8df7 1914 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1915 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1916 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 1917 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
1918}
1919
1920sub set_tree_cb {
1921 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
1922 $self->{inject_parents} = { $rev => $tree };
1923 $self->fetch(undef, undef);
9b981fc6
EW
1924}
1925
1926sub set_tree {
1927 my ($self, $tree) = (shift, shift);
1ce255dc 1928 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1929 unless ($self->{last_rev}) {
1930 fatal("Must have an existing revision to commit\n");
1931 }
61395354
EW
1932 my %ed_opts = ( r => $self->{last_rev},
1933 log => $log_entry->{log},
1934 ra => $self->ra,
1935 tree_a => $self->{last_commit},
1936 tree_b => $tree,
1937 editor_cb => sub {
1938 $self->set_tree_cb($log_entry, $tree, @_) },
1939 svn_path => $self->{path} );
1940 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1941 print "No changes\nr$self->{last_rev} = $tree\n";
1942 }
9b981fc6
EW
1943}
1944
f0ecca10
EW
1945sub rebuild {
1946 my ($self) = @_;
26a62d57 1947 my $db_path = $self->db_path;
d6d3346b
EW
1948 return if (-e $db_path && ! -z $db_path);
1949 return unless ::verify_ref($self->refname.'^0');
26a62d57
EW
1950 if (-f $self->{db_root}) {
1951 rename $self->{db_root}, $db_path or die
1952 "rename $self->{db_root} => $db_path failed: $!\n";
1953 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1954 symlink $base, $self->{db_root} or die
1955 "symlink $base => $self->{db_root} failed: $!\n";
1956 return;
1957 }
1958 print "Rebuilding $db_path ...\n";
f0ecca10
EW
1959 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1960 my $latest;
1961 my $full_url = $self->full_url;
18ea92bd 1962 remove_username($full_url);
f0ecca10
EW
1963 my $svn_uuid;
1964 while (<$rev_list>) {
1965 chomp;
1966 my $c = $_;
1967 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1968 my ($url, $rev, $uuid) = ::cmt_metadata($c);
18ea92bd 1969 remove_username($url);
f0ecca10
EW
1970
1971 # ignore merges (from set-tree)
1972 next if (!defined $rev || !$uuid);
1973
1974 # if we merged or otherwise started elsewhere, this is
1975 # how we break out of it
1976 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1977 ($full_url && $url && ($url ne $full_url))) {
1978 next;
1979 }
1980 $latest ||= $rev;
1981 $svn_uuid ||= $uuid;
1982
1983 $self->rev_db_set($rev, $c);
1984 print "r$rev = $c\n";
1985 }
1986 command_close_pipe($rev_list, $ctx);
26a62d57 1987 print "Done rebuilding $db_path\n";
f0ecca10
EW
1988}
1989
9b981fc6
EW
1990# rev_db:
1991# Tie::File seems to be prone to offset errors if revisions get sparse,
1992# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1993# one of my favorite modules is out :< Next up would be one of the DBM
1994# modules, but I'm not sure which is most portable... So I'll just
1995# go with something that's plain-text, but still capable of
1996# being randomly accessed. So here's my ultra-simple fixed-width
1997# database. All records are 40 characters + "\n", so it's easy to seek
1998# to a revision: (41 * rev) is the byte offset.
1999# A record of 40 0s denotes an empty revision.
2000# And yes, it's still pretty fast (faster than Tie::File).
97ae0911 2001# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2002
26a62d57
EW
2003sub _rev_db_set {
2004 my ($fh, $rev, $commit) = @_;
2005 my $offset = $rev * 41;
2006 # assume that append is the common case:
2007 seek $fh, 0, 2 or croak $!;
2008 my $pos = tell $fh;
2009 if ($pos < $offset) {
2010 for (1 .. (($offset - $pos) / 41)) {
2011 print $fh (('0' x 40),"\n") or croak $!;
2012 }
2013 }
2014 seek $fh, $offset, 0 or croak $!;
2015 print $fh $commit,"\n" or croak $!;
2016}
2017
2018sub mkfile {
2019 my ($path) = @_;
2020 unless (-e $path) {
2021 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2022 mkpath([$dir]) unless -d $dir;
2023 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2024 close $fh or die "Couldn't close (create) $path: $!\n";
2025 }
2026}
2027
9b981fc6 2028sub rev_db_set {
26a62d57
EW
2029 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2030 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2031 my $db = $self->db_path($uuid);
2032 my $db_lock = "$db.lock";
373274f9
EW
2033 my $sig;
2034 if ($update_ref) {
2035 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2036 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2037 }
26a62d57
EW
2038 mkfile($db);
2039
373274f9 2040 $LOCKFILES{$db_lock} = 1;
97ae0911 2041 my $sync;
97ae0911
EW
2042 # both of these options make our .rev_db file very, very important
2043 # and we can't afford to lose it because rebuild() won't work
2044 if ($self->use_svm_props || $self->no_metadata) {
2045 $sync = 1;
373274f9 2046 copy($db, $db_lock) or die "rev_db_set(@_): ",
26a62d57 2047 "Failed to copy: ",
373274f9
EW
2048 "$db => $db_lock ($!)\n";
2049 } else {
2050 rename $db, $db_lock or die "rev_db_set(@_): ",
26a62d57 2051 "Failed to rename: ",
373274f9
EW
2052 "$db => $db_lock ($!)\n";
2053 }
26a62d57
EW
2054 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2055 _rev_db_set($fh, $rev, $commit);
97ae0911
EW
2056 if ($sync) {
2057 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2058 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2059 }
9b981fc6 2060 close $fh or croak $!;
373274f9 2061 if ($update_ref) {
1e889ef3 2062 $_head = $self;
373274f9
EW
2063 command_noisy('update-ref', '-m', "r$rev",
2064 $self->refname, $commit);
2065 }
2066 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2067 "$db_lock => $db ($!)\n";
2068 delete $LOCKFILES{$db_lock};
2069 if ($update_ref) {
2070 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2071 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2072 kill $sig, $$ if defined $sig;
2073 }
9b981fc6
EW
2074}
2075
9c93fee5
EW
2076sub rev_db_max {
2077 my ($self) = @_;
d6d3346b 2078 $self->rebuild;
26a62d57
EW
2079 my $db_path = $self->db_path;
2080 my @stat = stat $db_path or return 0;
2081 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
9c93fee5
EW
2082 my $max = $stat[7] / 41;
2083 (($max > 0) ? $max - 1 : 0);
2084}
2085
9b981fc6 2086sub rev_db_get {
26a62d57 2087 my ($self, $rev, $uuid) = @_;
9b981fc6
EW
2088 my $ret;
2089 my $offset = $rev * 41;
26a62d57
EW
2090 my $db_path = $self->db_path($uuid);
2091 return undef unless -e $db_path;
2092 open my $fh, '<', $db_path or croak $!;
ce4b4af7
EW
2093 if (sysseek($fh, $offset, 0) == $offset) {
2094 my $read = sysread($fh, $ret, 40);
2095 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
2096 }
2097 close $fh or croak $!;
2098 $ret;
2099}
2100
15710b6f
EW
2101sub find_rev_before {
2102 my ($self, $rev, $eq_ok) = @_;
2103 --$rev unless $eq_ok;
2104 while ($rev > 0) {
2105 if (my $c = $self->rev_db_get($rev)) {
2106 return ($rev, $c);
2107 }
2108 --$rev;
2109 }
2110 return (undef, undef);
2111}
2112
9b981fc6 2113sub _new {
706587fc
EW
2114 my ($class, $repo_id, $ref_id, $path) = @_;
2115 unless (defined $repo_id && length $repo_id) {
2116 $repo_id = $Git::SVN::default_repo_id;
2117 }
2118 unless (defined $ref_id && length $ref_id) {
8b8fc068 2119 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
2120 }
2121 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2122 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2123 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2124 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2125 bless {
2126 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2127 path => $path, config => "$ENV{GIT_DIR}/svn/config",
26a62d57
EW
2128 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2129}
2130
2131sub db_path {
2132 my ($self, $uuid) = @_;
2133 $uuid ||= $self->ra_uuid;
2134 "$self->{db_root}.$uuid";
9b981fc6
EW
2135}
2136
1c8443b0
EW
2137sub uri_encode {
2138 my ($f) = @_;
2139 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2140 $f
2141}
9b981fc6 2142
18ea92bd
SV
2143sub remove_username {
2144 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2145}
2146
d976acfd
EW
2147package Git::SVN::Prompt;
2148use strict;
2149use warnings;
2150require SVN::Core;
2151use vars qw/$_no_auth_cache $_username/;
2152
2153sub simple {
30d055aa
EW
2154 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2155 $may_save = undef if $_no_auth_cache;
2156 $default_username = $_username if defined $_username;
2157 if (defined $default_username && length $default_username) {
2158 if (defined $realm && length $realm) {
6f729591
EW
2159 print STDERR "Authentication realm: $realm\n";
2160 STDERR->flush;
30d055aa
EW
2161 }
2162 $cred->username($default_username);
2163 } else {
d976acfd 2164 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2165 }
2166 $cred->password(_read_password("Password for '" .
2167 $cred->username . "': ", $realm));
2168 $cred->may_save($may_save);
2169 $SVN::_Core::SVN_NO_ERROR;
2170}
2171
d976acfd 2172sub ssl_server_trust {
30d055aa
EW
2173 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2174 $may_save = undef if $_no_auth_cache;
6f729591 2175 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 2176 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 2177 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
2178 "authority. Use the\n",
2179 " fingerprint to validate the certificate manually!\n";
2180 }
2181 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 2182 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
2183 }
2184 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 2185 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
2186 }
2187 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 2188 print STDERR " - The certificate has expired.\n";
30d055aa
EW
2189 }
2190 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 2191 print STDERR " - The certificate has an unknown error.\n";
30d055aa 2192 }
6f729591
EW
2193 printf STDERR
2194 "Certificate information:\n".
30d055aa
EW
2195 " - Hostname: %s\n".
2196 " - Valid: from %s until %s\n".
2197 " - Issuer: %s\n".
2198 " - Fingerprint: %s\n",
2199 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 2200 issuer_dname fingerprint);
30d055aa
EW
2201 my $choice;
2202prompt:
6f729591 2203 print STDERR $may_save ?
30d055aa
EW
2204 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2205 "(R)eject or accept (t)emporarily? ";
6f729591 2206 STDERR->flush;
30d055aa
EW
2207 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2208 if ($choice =~ /^t$/i) {
2209 $cred->may_save(undef);
2210 } elsif ($choice =~ /^r$/i) {
2211 return -1;
2212 } elsif ($may_save && $choice =~ /^p$/i) {
2213 $cred->may_save($may_save);
2214 } else {
2215 goto prompt;
2216 }
2217 $cred->accepted_failures($failures);
2218 $SVN::_Core::SVN_NO_ERROR;
2219}
2220
d976acfd 2221sub ssl_client_cert {
30d055aa
EW
2222 my ($cred, $realm, $may_save, $pool) = @_;
2223 $may_save = undef if $_no_auth_cache;
6f729591
EW
2224 print STDERR "Client certificate filename: ";
2225 STDERR->flush;
30d055aa
EW
2226 chomp(my $filename = <STDIN>);
2227 $cred->cert_file($filename);
2228 $cred->may_save($may_save);
2229 $SVN::_Core::SVN_NO_ERROR;
2230}
2231
d976acfd 2232sub ssl_client_cert_pw {
30d055aa
EW
2233 my ($cred, $realm, $may_save, $pool) = @_;
2234 $may_save = undef if $_no_auth_cache;
2235 $cred->password(_read_password("Password: ", $realm));
2236 $cred->may_save($may_save);
2237 $SVN::_Core::SVN_NO_ERROR;
2238}
2239
d976acfd 2240sub username {
30d055aa
EW
2241 my ($cred, $realm, $may_save, $pool) = @_;
2242 $may_save = undef if $_no_auth_cache;
2243 if (defined $realm && length $realm) {
6f729591 2244 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
2245 }
2246 my $username;
2247 if (defined $_username) {
2248 $username = $_username;
2249 } else {
6f729591
EW
2250 print STDERR "Username: ";
2251 STDERR->flush;
30d055aa
EW
2252 chomp($username = <STDIN>);
2253 }
2254 $cred->username($username);
2255 $cred->may_save($may_save);
2256 $SVN::_Core::SVN_NO_ERROR;
2257}
2258
2259sub _read_password {
2260 my ($prompt, $realm) = @_;
6f729591
EW
2261 print STDERR $prompt;
2262 STDERR->flush;
30d055aa
EW
2263 require Term::ReadKey;
2264 Term::ReadKey::ReadMode('noecho');
2265 my $password = '';
2266 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2267 last if $key =~ /[\012\015]/; # \n\r
2268 $password .= $key;
2269 }
2270 Term::ReadKey::ReadMode('restore');
6f729591
EW
2271 print STDERR "\n";
2272 STDERR->flush;
30d055aa
EW
2273 $password;
2274}
2275
d976acfd
EW
2276package main;
2277
b9c85187
EW
2278{
2279 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2280 $SVN::Node::dir.$SVN::Node::unknown.
2281 $SVN::Node::none.$SVN::Node::file.
2282 $SVN::Node::dir.$SVN::Node::unknown.
2283 $SVN::Auth::SSL::CNMISMATCH.
2284 $SVN::Auth::SSL::NOTYETVALID.
2285 $SVN::Auth::SSL::EXPIRED.
2286 $SVN::Auth::SSL::UNKNOWNCA.
2287 $SVN::Auth::SSL::OTHER;
2288}
2289
27a1a801
EW
2290package SVN::Git::Fetcher;
2291use vars qw/@ISA/;
2292use strict;
2293use warnings;
2294use Carp qw/croak/;
2295use IO::File qw//;
90c1b15d 2296use Digest::MD5;
27a1a801
EW
2297
2298# file baton members: path, mode_a, mode_b, pool, fh, blob, base
2299sub new {
2300 my ($class, $git_svn) = @_;
2301 my $self = SVN::Delta::Editor->new;
2302 bless $self, $class;
1c8443b0 2303 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
2304 $self->{empty} = {};
2305 $self->{dir_prop} = {};
2306 $self->{file_prop} = {};
2307 $self->{absent_dir} = {};
2308 $self->{absent_file} = {};
ef3cfaad 2309 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
2310 $self;
2311}
2312
8b8fc068
EW
2313sub set_path_strip {
2314 my ($self, $path) = @_;
4e9f6cc7 2315 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
2316}
2317
d2a9a87b
EW
2318sub open_root {
2319 { path => '' };
2320}
2321
2322sub open_directory {
2323 my ($self, $path, $pb, $rev) = @_;
2324 { path => $path };
2325}
2326
706587fc
EW
2327sub git_path {
2328 my ($self, $path) = @_;
2b27f6c8
EW
2329 if ($self->{path_strip}) {
2330 $path =~ s!$self->{path_strip}!! or
2331 die "Failed to strip path '$path' ($self->{path_strip})\n";
2332 }
706587fc
EW
2333 $path;
2334}
2335
27a1a801
EW
2336sub delete_entry {
2337 my ($self, $path, $rev, $pb) = @_;
4a87db0e 2338
706587fc 2339 my $gpath = $self->git_path($path);
8a603774
EW
2340 return undef if ($gpath eq '');
2341
4a87db0e 2342 # remove entire directories.
706587fc 2343 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
2344 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2345 -r --name-only -z/,
706587fc 2346 $self->{c}, '--', $gpath);
4a87db0e
EW
2347 local $/ = "\0";
2348 while (<$ls>) {
ef3cfaad
EW
2349 chomp;
2350 $self->{gii}->remove($_);
9e3cdbd4 2351 print "\tD\t$_\n" unless $::_q;
4a87db0e 2352 }
9e3cdbd4 2353 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
2354 command_close_pipe($ls, $ctx);
2355 $self->{empty}->{$path} = 0
2356 } else {
ef3cfaad 2357 $self->{gii}->remove($gpath);
9e3cdbd4 2358 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 2359 }
27a1a801
EW
2360 undef;
2361}
2362
2363sub open_file {
2364 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
2365 my $gpath = $self->git_path($path);
2366 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 2367 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
2368 unless (defined $mode && defined $blob) {
2369 die "$path was not found in commit $self->{c} (r$rev)\n";
2370 }
27a1a801 2371 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 2372 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
2373}
2374
2375sub add_file {
2376 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
2377 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2378 delete $self->{empty}->{$dir};
27a1a801 2379 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 2380 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
2381}
2382
d2a9a87b
EW
2383sub add_directory {
2384 my ($self, $path, $cp_path, $cp_rev) = @_;
2385 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2386 delete $self->{empty}->{$dir};
2387 $self->{empty}->{$path} = 1;
2388 { path => $path };
2389}
2390
2391sub change_dir_prop {
2392 my ($self, $db, $prop, $value) = @_;
2393 $self->{dir_prop}->{$db->{path}} ||= {};
2394 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2395 undef;
2396}
2397
2398sub absent_directory {
2399 my ($self, $path, $pb) = @_;
2400 $self->{absent_dir}->{$pb->{path}} ||= [];
2401 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2402 undef;
2403}
2404
2405sub absent_file {
2406 my ($self, $path, $pb) = @_;
2407 $self->{absent_file}->{$pb->{path}} ||= [];
2408 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2409 undef;
2410}
2411
27a1a801
EW
2412sub change_file_prop {
2413 my ($self, $fb, $prop, $value) = @_;
2414 if ($prop eq 'svn:executable') {
2415 if ($fb->{mode_b} != 120000) {
2416 $fb->{mode_b} = defined $value ? 100755 : 100644;
2417 }
2418 } elsif ($prop eq 'svn:special') {
2419 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
2420 } else {
2421 $self->{file_prop}->{$fb->{path}} ||= {};
2422 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
2423 }
2424 undef;
2425}
2426
2427sub apply_textdelta {
2428 my ($self, $fb, $exp) = @_;
2429 my $fh = IO::File->new_tmpfile;
2430 $fh->autoflush(1);
2431 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2432 # (but $base does not,) so dup() it for reading in close_file
2433 open my $dup, '<&', $fh or croak $!;
2434 my $base = IO::File->new_tmpfile;
2435 $base->autoflush(1);
2436 if ($fb->{blob}) {
2437 defined (my $pid = fork) or croak $!;
2438 if (!$pid) {
2439 open STDOUT, '>&', $base or croak $!;
2440 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2441 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2442 }
2443 waitpid $pid, 0;
2444 croak $? if $?;
2445
2446 if (defined $exp) {
2447 seek $base, 0, 0 or croak $!;
2448 my $md5 = Digest::MD5->new;
2449 $md5->addfile($base);
2450 my $got = $md5->hexdigest;
2451 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2452 "expected: $exp\n",
2453 " got: $got\n" if ($got ne $exp);
2454 }
2455 }
2456 seek $base, 0, 0 or croak $!;
2457 $fb->{fh} = $dup;
2458 $fb->{base} = $base;
2459 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2460}
2461
2462sub close_file {
2463 my ($self, $fb, $exp) = @_;
2464 my $hash;
706587fc 2465 my $path = $self->git_path($fb->{path});
27a1a801
EW
2466 if (my $fh = $fb->{fh}) {
2467 seek($fh, 0, 0) or croak $!;
2468 my $md5 = Digest::MD5->new;
2469 $md5->addfile($fh);
2470 my $got = $md5->hexdigest;
2471 die "Checksum mismatch: $path\n",
2472 "expected: $exp\n got: $got\n" if ($got ne $exp);
bcd8ee5b 2473 sysseek($fh, 0, 0) or croak $!;
27a1a801 2474 if ($fb->{mode_b} == 120000) {
bcd8ee5b 2475 sysread($fh, my $buf, 5) == 5 or croak $!;
27a1a801
EW
2476 $buf eq 'link ' or die "$path has mode 120000",
2477 "but is not a link\n";
2478 }
2479 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2480 if (!$pid) {
2481 open STDIN, '<&', $fh or croak $!;
2482 exec qw/git-hash-object -w --stdin/ or croak $!;
2483 }
2484 chomp($hash = do { local $/; <$out> });
2485 close $out or croak $!;
2486 close $fh or croak $!;
2487 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2488 close $fb->{base} or croak $!;
2489 } else {
2490 $hash = $fb->{blob} or die "no blob information\n";
2491 }
2492 $fb->{pool}->clear;
ef3cfaad 2493 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 2494 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
2495 undef;
2496}
2497
2498sub abort_edit {
2499 my $self = shift;
ef3cfaad
EW
2500 $self->{nr} = $self->{gii}->{nr};
2501 delete $self->{gii};
27a1a801
EW
2502 $self->SUPER::abort_edit(@_);
2503}
2504
2505sub close_edit {
2506 my $self = shift;
dad73c0b 2507 $self->{git_commit_ok} = 1;
ef3cfaad
EW
2508 $self->{nr} = $self->{gii}->{nr};
2509 delete $self->{gii};
27a1a801
EW
2510 $self->SUPER::close_edit(@_);
2511}
1a82e793 2512
a5e0cedc 2513package SVN::Git::Editor;
24e22aa8 2514use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
2515use strict;
2516use warnings;
2517use Carp qw/croak/;
2518use IO::File;
90c1b15d 2519use Digest::MD5;
a5e0cedc
EW
2520
2521sub new {
61395354
EW
2522 my ($class, $opts) = @_;
2523 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2524 die "$_ required!\n" unless (defined $opts->{$_});
2525 }
2526
2527 my $pool = SVN::Pool->new;
2528 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2529 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2530 $opts->{r}, $mods);
2531
2532 # $opts->{ra} functions should not be used after this:
2533 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2534 $opts->{editor_cb}, $pool);
2535 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 2536 bless $self, $class;
61395354
EW
2537 foreach (qw/svn_path r tree_a tree_b/) {
2538 $self->{$_} = $opts->{$_};
a5e0cedc 2539 }
61395354
EW
2540 $self->{url} = $opts->{ra}->{url};
2541 $self->{mods} = $mods;
2542 $self->{types} = $types;
2543 $self->{pool} = $pool;
a5e0cedc
EW
2544 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2545 $self->{rm} = { };
d3a840dc
EW
2546 $self->{path_prefix} = length $self->{svn_path} ?
2547 "$self->{svn_path}/" : '';
a5e0cedc
EW
2548 return $self;
2549}
2550
61395354
EW
2551sub generate_diff {
2552 my ($tree_a, $tree_b) = @_;
2553 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
2554 if ($_cp_similarity) {
2555 push @diff_tree, "-C$_cp_similarity";
61395354
EW
2556 } else {
2557 push @diff_tree, '-C';
2558 }
24e22aa8
EW
2559 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2560 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
2561 push @diff_tree, $tree_a, $tree_b;
2562 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2563 local $/ = "\0";
2564 my $state = 'meta';
2565 my @mods;
2566 while (<$diff_fh>) {
2567 chomp $_; # this gets rid of the trailing "\0"
2568 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2569 $::sha1\s($::sha1)\s
2570 ([MTCRAD])\d*$/xo) {
2571 push @mods, { mode_a => $1, mode_b => $2,
2572 sha1_b => $3, chg => $4 };
2573 if ($4 =~ /^(?:C|R)$/) {
2574 $state = 'file_a';
2575 } else {
2576 $state = 'file_b';
2577 }
2578 } elsif ($state eq 'file_a') {
2579 my $x = $mods[$#mods] or croak "Empty array\n";
2580 if ($x->{chg} !~ /^(?:C|R)$/) {
2581 croak "Error parsing $_, $x->{chg}\n";
2582 }
2583 $x->{file_a} = $_;
2584 $state = 'file_b';
2585 } elsif ($state eq 'file_b') {
2586 my $x = $mods[$#mods] or croak "Empty array\n";
2587 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2588 croak "Error parsing $_, $x->{chg}\n";
2589 }
2590 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2591 croak "Error parsing $_, $x->{chg}\n";
2592 }
2593 $x->{file_b} = $_;
2594 $state = 'meta';
2595 } else {
2596 croak "Error parsing $_\n";
2597 }
2598 }
2599 command_close_pipe($diff_fh, $ctx);
2600 \@mods;
2601}
2602
2603sub check_diff_paths {
2604 my ($ra, $pfx, $rev, $mods) = @_;
2605 my %types;
2606 $pfx .= '/' if length $pfx;
2607
2608 sub type_diff_paths {
2609 my ($ra, $types, $path, $rev) = @_;
2610 my @p = split m#/+#, $path;
2611 my $c = shift @p;
2612 unless (defined $types->{$c}) {
2613 $types->{$c} = $ra->check_path($c, $rev);
2614 }
2615 while (@p) {
2616 $c .= '/' . shift @p;
2617 next if defined $types->{$c};
2618 $types->{$c} = $ra->check_path($c, $rev);
2619 }
2620 }
2621
2622 foreach my $m (@$mods) {
2623 foreach my $f (qw/file_a file_b/) {
2624 next unless defined $m->{$f};
2625 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2626 if (length $pfx.$dir && ! defined $types{$dir}) {
2627 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2628 }
2629 }
2630 }
2631 \%types;
2632}
2633
a5e0cedc
EW
2634sub split_path {
2635 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2636}
2637
2638sub repo_path {
d3a840dc
EW
2639 my ($self, $path) = @_;
2640 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2641}
2642
2643sub url_path {
2644 my ($self, $path) = @_;
6e8548cc 2645 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2646}
2647
2648sub rmdirs {
61395354 2649 my ($self) = @_;
a5e0cedc
EW
2650 my $rm = $self->{rm};
2651 delete $rm->{''}; # we never delete the url we're tracking
2652 return unless %$rm;
2653
2654 foreach (keys %$rm) {
2655 my @d = split m#/#, $_;
2656 my $c = shift @d;
2657 $rm->{$c} = 1;
2658 while (@d) {
2659 $c .= '/' . shift @d;
2660 $rm->{$c} = 1;
2661 }
2662 }
2663 delete $rm->{$self->{svn_path}};
2664 delete $rm->{''}; # we never delete the url we're tracking
2665 return unless %$rm;
2666
61395354
EW
2667 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2668 $self->{tree_b});
a5e0cedc
EW
2669 local $/ = "\0";
2670 while (<$fh>) {
2671 chomp;
747fa12c 2672 my @dn = split m#/#, $_;
c07eee1f
EW
2673 while (pop @dn) {
2674 delete $rm->{join '/', @dn};
2675 }
2676 unless (%$rm) {
22600a25 2677 close $fh;
c07eee1f
EW
2678 return;
2679 }
a5e0cedc 2680 }
aef4e921 2681 command_close_pipe($fh, $ctx);
c07eee1f 2682
a5e0cedc
EW
2683 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2684 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2685 $self->close_directory($bat->{$d}, $p);
2686 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2687 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2688 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2689 delete $bat->{$d};
2690 }
2691}
2692
2693sub open_or_add_dir {
2694 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2695 my $t = $self->{types}->{$full_path};
2696 if (!defined $t) {
2697 die "$full_path not known in r$self->{r} or we have a bug!\n";
2698 }
a5e0cedc
EW
2699 if ($t == $SVN::Node::none) {
2700 return $self->add_directory($full_path, $baton,
2701 undef, -1, $self->{pool});
2702 } elsif ($t == $SVN::Node::dir) {
2703 return $self->open_directory($full_path, $baton,
2704 $self->{r}, $self->{pool});
2705 }
2706 print STDERR "$full_path already exists in repository at ",
2707 "r$self->{r} and it is not a directory (",
2708 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2709 exit 1;
2710}
2711
2712sub ensure_path {
2713 my ($self, $path) = @_;
2714 my $bat = $self->{bat};
6e8548cc
EW
2715 my $repo_path = $self->repo_path($path);
2716 return $bat->{''} unless (length $repo_path);
2717 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2718 my $c = shift @p;
2719 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2720 while (@p) {
2721 my $c0 = $c;
2722 $c .= '/' . shift @p;
2723 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2724 }
2725 return $bat->{$c};
2726}
2727
2728sub A {
44320b9e 2729 my ($self, $m) = @_;
a5e0cedc
EW
2730 my ($dir, $file) = split_path($m->{file_b});
2731 my $pbat = $self->ensure_path($dir);
2732 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2733 undef, -1);
44320b9e 2734 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2735 $self->chg_file($fbat, $m);
2736 $self->close_file($fbat,undef,$self->{pool});
2737}
2738
2739sub C {
44320b9e 2740 my ($self, $m) = @_;
a5e0cedc
EW
2741 my ($dir, $file) = split_path($m->{file_b});
2742 my $pbat = $self->ensure_path($dir);
2743 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2744 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2745 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2746 $self->chg_file($fbat, $m);
2747 $self->close_file($fbat,undef,$self->{pool});
2748}
2749
2750sub delete_entry {
2751 my ($self, $path, $pbat) = @_;
2752 my $rpath = $self->repo_path($path);
2753 my ($dir, $file) = split_path($rpath);
2754 $self->{rm}->{$dir} = 1;
2755 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2756}
2757
2758sub R {
44320b9e 2759 my ($self, $m) = @_;
a5e0cedc
EW
2760 my ($dir, $file) = split_path($m->{file_b});
2761 my $pbat = $self->ensure_path($dir);
2762 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2763 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2764 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2765 $self->chg_file($fbat, $m);
2766 $self->close_file($fbat,undef,$self->{pool});
2767
2768 ($dir, $file) = split_path($m->{file_a});
2769 $pbat = $self->ensure_path($dir);
2770 $self->delete_entry($m->{file_a}, $pbat);
2771}
2772
2773sub M {
44320b9e 2774 my ($self, $m) = @_;
a5e0cedc
EW
2775 my ($dir, $file) = split_path($m->{file_b});
2776 my $pbat = $self->ensure_path($dir);
2777 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2778 $pbat,$self->{r},$self->{pool});
44320b9e 2779 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2780 $self->chg_file($fbat, $m);
2781 $self->close_file($fbat,undef,$self->{pool});
2782}
2783
2784sub T { shift->M(@_) }
2785
2786sub change_file_prop {
2787 my ($self, $fbat, $pname, $pval) = @_;
2788 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2789}
2790
2791sub chg_file {
2792 my ($self, $fbat, $m) = @_;
2793 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2794 $self->change_file_prop($fbat,'svn:executable','*');
2795 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2796 $self->change_file_prop($fbat,'svn:executable',undef);
2797 }
2798 my $fh = IO::File->new_tmpfile or croak $!;
2799 if ($m->{mode_b} =~ /^120/) {
2800 print $fh 'link ' or croak $!;
2801 $self->change_file_prop($fbat,'svn:special','*');
2802 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2803 $self->change_file_prop($fbat,'svn:special',undef);
2804 }
2805 defined(my $pid = fork) or croak $!;
2806 if (!$pid) {
2807 open STDOUT, '>&', $fh or croak $!;
2808 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2809 }
2810 waitpid $pid, 0;
2811 croak $? if $?;
2812 $fh->flush == 0 or croak $!;
2813 seek $fh, 0, 0 or croak $!;
2814
2815 my $md5 = Digest::MD5->new;
2816 $md5->addfile($fh) or croak $!;
2817 seek $fh, 0, 0 or croak $!;
2818
2819 my $exp = $md5->hexdigest;
f7197dff
EW
2820 my $pool = SVN::Pool->new;
2821 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2822 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2823 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2824 $pool->clear;
a5e0cedc
EW
2825
2826 close $fh or croak $!;
2827}
2828
2829sub D {
44320b9e 2830 my ($self, $m) = @_;
a5e0cedc
EW
2831 my ($dir, $file) = split_path($m->{file_b});
2832 my $pbat = $self->ensure_path($dir);
44320b9e 2833 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2834 $self->delete_entry($m->{file_b}, $pbat);
2835}
2836
2837sub close_edit {
2838 my ($self) = @_;
2839 my ($p,$bat) = ($self->{pool}, $self->{bat});
2840 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2841 $self->close_directory($bat->{$_}, $p);
2842 }
2843 $self->SUPER::close_edit($p);
2844 $p->clear;
2845}
2846
2847sub abort_edit {
2848 my ($self) = @_;
2849 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2850}
2851
2852sub DESTROY {
2853 my $self = shift;
2854 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2855 $self->{pool}->clear;
2856}
2857
44320b9e
EW
2858# this drives the editor
2859sub apply_diff {
61395354
EW
2860 my ($self) = @_;
2861 my $mods = $self->{mods};
44320b9e 2862 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2863 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2864 my $f = $m->{chg};
2865 if (defined $o{$f}) {
2866 $self->$f($m);
2867 } else {
2868 fatal("Invalid change type: $f\n");
2869 }
2870 }
24e22aa8 2871 $self->rmdirs if $_rmdir;
6e8548cc 2872 if (@$mods == 0) {
44320b9e
EW
2873 $self->abort_edit;
2874 } else {
2875 $self->close_edit;
2876 }
6e8548cc 2877 return scalar @$mods;
44320b9e
EW
2878}
2879
d81bf827 2880package Git::SVN::Ra;
6af1db44 2881use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
2882use strict;
2883use warnings;
a6a15a99 2884my ($can_do_switch, %ignored_err, $RA);
d81bf827
EW
2885
2886BEGIN {
2887 # enforce temporary pool usage for some simple functions
2888 my $e;
74a81227 2889 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
d81bf827
EW
2890 $e .= "sub $_ {
2891 my \$self = shift;
2892 my \$pool = SVN::Pool->new;
2893 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2894 \$pool->clear;
2895 wantarray ? \@ret : \$ret[0]; }\n";
2896 }
74a81227
EW
2897
2898 # get_dir needs $pool held in cache for dirents to work,
2899 # check_path is cacheable and rev_proplist is close enough
2900 # for our purposes.
2901 foreach (qw/check_path get_dir rev_proplist/) {
2902 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2903 my \$self = shift;
2904 my \$r = pop;
2905 my \$k = join(\"\\0\", \@_);
2906 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2907 return wantarray ? \@\$x : \$x->[0];
2908 }
2909 my \$pool = SVN::Pool->new;
2910 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2911 if (\$r != \$${_}_rev) {
2912 \%${_}_cache = ( pool => [] );
2913 \$${_}_rev = \$r;
2914 }
2915 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2916 push \@{\$${_}_cache{pool}}, \$pool;
2917 wantarray ? \@ret : \$ret[0]; }\n";
2918 }
2919 $e .= "\n1;";
2920 eval $e or die $@;
d81bf827
EW
2921}
2922
2923sub new {
2924 my ($class, $url) = @_;
f6f09876 2925 $url =~ s!/+$!!;
5d3b7cd5 2926 return $RA if ($RA && $RA->{url} eq $url);
e2c475d9 2927 $RA->{pool}->clear if $RA;
f6f09876 2928
d81bf827
EW
2929 SVN::_Core::svn_config_ensure($config_dir, undef);
2930 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2931 SVN::Client::get_simple_provider(),
2932 SVN::Client::get_ssl_server_trust_file_provider(),
2933 SVN::Client::get_simple_prompt_provider(
2934 \&Git::SVN::Prompt::simple, 2),
2935 SVN::Client::get_ssl_client_cert_prompt_provider(
2936 \&Git::SVN::Prompt::ssl_client_cert, 2),
2937 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2938 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2939 SVN::Client::get_username_provider(),
2940 SVN::Client::get_ssl_server_trust_prompt_provider(
2941 \&Git::SVN::Prompt::ssl_server_trust),
2942 SVN::Client::get_username_prompt_provider(
2943 \&Git::SVN::Prompt::username, 2),
2944 ]);
2945 my $config = SVN::Core::config_get_config($config_dir);
2946 my $self = SVN::Ra->new(url => $url, auth => $baton,
2947 config => $config,
2948 pool => SVN::Pool->new,
2949 auth_provider_callbacks => $callbacks);
2950 $self->{svn_path} = $url;
2951 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 2952 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5d3b7cd5 2953 $RA = bless $self, $class;
d81bf827
EW
2954}
2955
2956sub DESTROY {
5d3b7cd5 2957 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2958}
2959
d81bf827
EW
2960sub get_log {
2961 my ($self, @args) = @_;
2962 my $pool = SVN::Pool->new;
d81bf827
EW
2963 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2964 my $ret = $self->SUPER::get_log(@args, $pool);
2965 $pool->clear;
2966 $ret;
2967}
2968
2969sub get_commit_editor {
44320b9e 2970 my ($self, $log, $cb, $pool) = @_;
d81bf827 2971 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2972 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2973}
2974
d81bf827 2975sub gs_do_update {
8a603774
EW
2976 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2977 my $new = ($rev_a == $rev_b);
2978 my $path = $gs->{path};
2979
2e5e2480
EW
2980 if ($new && -e $gs->{index}) {
2981 unlink $gs->{index} or die
2982 "Couldn't unlink index: $gs->{index}: $!\n";
2983 }
d81bf827 2984 my $pool = SVN::Pool->new;
8b8fc068 2985 $editor->set_path_strip($path);
2b27f6c8
EW
2986 my (@pc) = split m#/#, $path;
2987 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 2988 1, $editor, $pool);
d81bf827 2989 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
2990
2991 # Since we can't rely on svn_ra_reparent being available, we'll
2992 # just have to do some magic with set_path to make it so
2993 # we only want a partial path.
2994 my $sp = '';
2995 my $final = join('/', @pc);
2996 while (@pc) {
2997 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2998 $sp .= '/' if length $sp;
2999 $sp .= shift @pc;
3000 }
3001 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3002
2b27f6c8
EW
3003 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3004
d81bf827
EW
3005 $reporter->finish_report($pool);
3006 $pool->clear;
3007 $editor->{git_commit_ok};
3008}
3009
2b27f6c8
EW
3010# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3011# svn_ra_reparent didn't work before 1.4)
d81bf827 3012sub gs_do_switch {
8a603774
EW
3013 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3014 my $path = $gs->{path};
d81bf827 3015 my $pool = SVN::Pool->new;
2b27f6c8
EW
3016
3017 my $full_url = $self->{url};
3018 my $old_url = $full_url;
3019 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
3020 my ($ra, $reparented);
3021 if ($old_url ne $full_url) {
3022 if ($old_url !~ m#^svn(\+ssh)?://#) {
3023 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3024 $pool);
3025 $self->{url} = $full_url;
3026 $reparented = 1;
3027 } else {
3028 $ra = Git::SVN::Ra->new($full_url);
3029 }
3030 }
3031 $ra ||= $self;
8a603774 3032 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 3033 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 3034 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 3035 $reporter->finish_report($pool);
2b27f6c8 3036
5d3b7cd5
EW
3037 if ($reparented) {
3038 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3039 $self->{url} = $old_url;
3040 }
2b27f6c8 3041
d81bf827
EW
3042 $pool->clear;
3043 $editor->{git_commit_ok};
3044}
3045
0af9c9f9 3046sub gs_fetch_loop_common {
e518192f
EW
3047 my ($self, $base, $head, $gsv, $globs) = @_;
3048 return if ($base > $head);
6af1db44 3049 my $inc = $_log_window_size;
0af9c9f9 3050 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
d2ae1434 3051 my %common;
e518192f
EW
3052 my $common_max = scalar @$gsv;
3053
3054 foreach my $gs (@$gsv) {
d2ae1434
EW
3055 my @tmp = split m#/#, $gs->{path};
3056 my $p = '';
3057 foreach (@tmp) {
3058 $p .= length($p) ? "/$_" : $_;
3059 $common{$p} ||= 0;
3060 $common{$p}++;
3061 }
3062 }
e518192f
EW
3063 $globs ||= [];
3064 $common_max += scalar @$globs;
3065 foreach my $glob (@$globs) {
3066 my @tmp = split m#/#, $glob->{path}->{left};
3067 my $p = '';
3068 foreach (@tmp) {
3069 $p .= length($p) ? "/$_" : $_;
3070 $common{$p} ||= 0;
3071 $common{$p}++;
3072 }
3073 }
3074
d2ae1434
EW
3075 my $longest_path = '';
3076 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 3077 if ($common{$_} == $common_max) {
d2ae1434
EW
3078 $longest_path = $_;
3079 last;
3080 }
0af9c9f9
EW
3081 }
3082 while (1) {
d4eff2bd 3083 my %revs;
d2ae1434 3084 my $err;
f7c3fc4a 3085 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
3086 $SVN::Error::handler = sub {
3087 ($err) = @_;
3088 skip_unknown_revs($err);
3089 };
3090 sub _cb {
3091 my ($paths, $r, $author, $date, $log) = @_;
3092 [ dup_changed_paths($paths),
3093 { author => $author, date => $date, log => $log } ];
3094 }
3095 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3096 sub { $revs{$_[1]} = _cb(@_) });
3097 if ($err && $max >= $head) {
3098 print STDERR "Path '$longest_path' ",
3099 "was probably deleted:\n",
3100 $err->expanded_message,
3101 "\nWill attempt to follow ",
3102 "revisions r$min .. r$max ",
3103 "committed before the deletion\n";
3104 my $hi = $max;
3105 while (--$hi >= $min) {
3106 my $ok;
3107 $self->get_log([$longest_path], $min, $hi,
3108 0, 1, 1, sub {
3109 $ok ||= $_[1];
3110 $revs{$_[1]} = _cb(@_) });
3111 if ($ok) {
3112 print STDERR "r$min .. r$ok OK\n";
3113 last;
3114 }
3115 }
3116 }
d4eff2bd 3117 $SVN::Error::handler = $err_handler;
fbcc1737 3118
e518192f 3119 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 3120 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 3121 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
3122
3123 foreach my $gs ($self->match_globs(\%exists, $paths,
3124 $globs, $r)) {
fbcc1737
EW
3125 if ($gs->rev_db_max >= $r) {
3126 next;
3127 }
3128 next unless $gs->match_paths($paths, $r);
3129 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
3130 if (my $last_commit = $gs->last_commit) {
3131 $gs->assert_index_clean($last_commit);
3132 }
fbcc1737
EW
3133 my $log_entry = $gs->do_fetch($paths, $r);
3134 if ($log_entry) {
0af9c9f9
EW
3135 $gs->do_git_commit($log_entry);
3136 }
3137 }
e518192f 3138 foreach my $g (@$globs) {
93f2689c
EW
3139 my $k = "svn-remote.$g->{remote}." .
3140 "$g->{t}-maxRev";
3141 Git::SVN::tmp_config($k, $r);
e518192f 3142 }
0af9c9f9 3143 }
9c93fee5
EW
3144 # pre-fill the .rev_db since it'll eventually get filled in
3145 # with '0' x40 if something new gets committed
e518192f 3146 foreach my $gs (@$gsv) {
9c93fee5
EW
3147 next if defined $gs->rev_db_get($max);
3148 $gs->rev_db_set($max, 0 x40);
3149 }
c3560e53
EW
3150 foreach my $g (@$globs) {
3151 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3152 Git::SVN::tmp_config($k, $max);
3153 }
0af9c9f9
EW
3154 last if $max >= $head;
3155 $min = $max + 1;
3156 $max += $inc;
3157 $max = $head if ($max > $head);
3158 }
0af9c9f9
EW
3159}
3160
e518192f
EW
3161sub match_globs {
3162 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
3163
3164 sub get_dir_check {
3165 my ($self, $exists, $g, $r) = @_;
3166 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3167 return unless scalar @x == 3;
3168 my $dirents = $x[0];
3169 foreach my $de (keys %$dirents) {
3170 next if $dirents->{$de}->kind != $SVN::Node::dir;
3171 my $p = $g->{path}->full_path($de);
3172 next if $exists->{$p};
3173 next if (length $g->{path}->{right} &&
3174 ($self->check_path($p, $r) !=
3175 $SVN::Node::dir));
3176 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3177 $g->{ref}->full_path($de), 1);
3178 }
3179 }
e518192f 3180 foreach my $g (@$globs) {
74a81227
EW
3181 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3182 if ($path->{action} =~ /^[AR]$/) {
3183 get_dir_check($self, $exists, $g, $r);
3184 }
3185 }
e518192f 3186 foreach (keys %$paths) {
28710f74
EW
3187 if (/$g->{path}->{left_regex}/ &&
3188 !/$g->{path}->{regex}/) {
74a81227
EW
3189 next if $paths->{$_}->{action} !~ /^[AR]$/;
3190 get_dir_check($self, $exists, $g, $r);
3191 }
e518192f
EW
3192 next unless /$g->{path}->{regex}/;
3193 my $p = $1;
3194 my $pathname = $g->{path}->full_path($p);
3195 next if $exists->{$pathname};
0c1ec5a1
EW
3196 next if ($self->check_path($pathname, $r) !=
3197 $SVN::Node::dir);
e518192f
EW
3198 $exists->{$pathname} = Git::SVN->init(
3199 $self->{url}, $pathname, undef,
3200 $g->{ref}->full_path($p), 1);
3201 }
3202 my $c = '';
3203 foreach (split m#/#, $g->{path}->{left}) {
3204 $c .= "/$_";
3205 next unless ($paths->{$c} &&
74a81227
EW
3206 ($paths->{$c}->{action} =~ /^[AR]$/));
3207 get_dir_check($self, $exists, $g, $r);
e518192f
EW
3208 }
3209 }
3210 values %$exists;
3211}
3212
e6434f87
EW
3213sub minimize_url {
3214 my ($self) = @_;
3215 return $self->{url} if ($self->{url} eq $self->{repos_root});
3216 my $url = $self->{repos_root};
3217 my @components = split(m!/!, $self->{svn_path});
3218 my $c = '';
3219 do {
3220 $url .= "/$c" if length $c;
3221 eval { (ref $self)->new($url)->get_latest_revnum };
3222 } while ($@ && ($c = shift @components));
3223 $url;
3224}
3225
d81bf827
EW
3226sub can_do_switch {
3227 my $self = shift;
3228 unless (defined $can_do_switch) {
3229 my $pool = SVN::Pool->new;
3230 my $rep = eval {
3231 $self->do_switch(1, '', 0, $self->{url},
3232 SVN::Delta::Editor->new, $pool);
3233 };
3234 if ($@) {
3235 $can_do_switch = 0;
3236 } else {
3237 $rep->abort_report($pool);
3238 $can_do_switch = 1;
3239 }
3240 $pool->clear;
3241 }
3242 $can_do_switch;
3243}
3244
0af9c9f9
EW
3245sub skip_unknown_revs {
3246 my ($err) = @_;
3247 my $errno = $err->apr_err();
3248 # Maybe the branch we're tracking didn't
3249 # exist when the repo started, so it's
3250 # not an error if it doesn't, just continue
3251 #
3252 # Wonderfully consistent library, eh?
3253 # 160013 - svn:// and file://
3254 # 175002 - http(s)://
3255 # 175007 - http(s):// (this repo required authorization, too...)
3256 # More codes may be discovered later...
3257 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
3258 my $err_key = $err->expanded_message;
3259 # revision numbers change every time, filter them out
3260 $err_key =~ s/\d+/\0/g;
3261 $err_key = "$errno\0$err_key";
3262 unless ($ignored_err{$err_key}) {
3263 warn "W: Ignoring error from SVN, path probably ",
3264 "does not exist: ($errno): ",
3265 $err->expanded_message,"\n";
3266 $ignored_err{$err_key} = 1;
3267 }
0af9c9f9
EW
3268 return;
3269 }
3270 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3271}
3272
3273# svn_log_changed_path_t objects passed to get_log are likely to be
3274# overwritten even if only the refs are copied to an external variable,
3275# so we should dup the structures in their entirety. Using an externally
3276# passed pool (instead of our temporary and quickly cleared pool in
3277# Git::SVN::Ra) does not help matters at all...
3278sub dup_changed_paths {
3279 my ($paths) = @_;
3280 return undef unless $paths;
3281 my %ret;
3282 foreach my $p (keys %$paths) {
3283 my $i = $paths->{$p};
3284 my %s = map { $_ => $i->$_ }
3285 qw/copyfrom_path copyfrom_rev action/;
3286 $ret{$p} = \%s;
3287 }
3288 \%ret;
3289}
3290
f8c9d1d2
EW
3291package Git::SVN::Log;
3292use strict;
3293use warnings;
3294use POSIX qw/strftime/;
3295use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3296 %rusers $show_commit $incremental/;
3297my $l_fmt;
3298
3299sub cmt_showable {
3300 my ($c) = @_;
3301 return 1 if defined $c->{r};
c16d0871
EW
3302
3303 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
3304 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3305 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 3306 @{$c->{l}} = ();
44320b9e 3307 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
3308
3309 # shift off the headers
3310 shift @log while ($log[0] ne '');
44320b9e 3311 shift @log;
c16d0871
EW
3312
3313 # TODO: make $c->{l} not have a trailing newline in the future
3314 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
3315
3316 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 3317 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
3318 }
3319 return defined $c->{r};
3320}
3321
3322sub log_use_color {
3323 return 1 if $color;
3324 my ($dc, $dcvar);
3325 $dcvar = 'color.diff';
3326 $dc = `git-config --get $dcvar`;
3327 if ($dc eq '') {
3328 # nothing at all; fallback to "diff.color"
3329 $dcvar = 'diff.color';
3330 $dc = `git-config --get $dcvar`;
3331 }
3332 chomp($dc);
3333 if ($dc eq 'auto') {
3334 my $pc;
3335 $pc = `git-config --get color.pager`;
3336 if ($pc eq '') {
3337 # does not have it -- fallback to pager.color
3338 $pc = `git-config --bool --get pager.color`;
3339 }
3340 else {
3341 $pc = `git-config --bool --get color.pager`;
3342 if ($?) {
3343 $pc = 'false';
3344 }
3345 }
3346 chomp($pc);
3347 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3348 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3349 }
3350 return 0;
3351 }
3352 return 0 if $dc eq 'never';
3353 return 1 if $dc eq 'always';
3354 chomp($dc = `git-config --bool --get $dcvar`);
3355 return ($dc eq 'true');
3356}
3357
3358sub git_svn_log_cmd {
3bc718ba
EW
3359 my ($r_min, $r_max, @args) = @_;
3360 my $head = 'HEAD';
3361 foreach my $x (@args) {
3362 last if $x eq '--';
3363 next unless ::verify_ref("$x^0");
3364 $head = $x;
3365 last;
3366 }
3367
13c823fb
EW
3368 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3369 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
3370 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3371 $gs->refname);
3372 push @cmd, '-r' unless $non_recursive;
3373 push @cmd, qw/--raw --name-status/ if $verbose;
3374 push @cmd, '--color' if log_use_color();
3375 return @cmd unless defined $r_max;
3376 if ($r_max == $r_min) {
3377 push @cmd, '--max-count=1';
3378 if (my $c = $gs->rev_db_get($r_max)) {
3379 push @cmd, $c;
3380 }
3381 } else {
3382 my ($c_min, $c_max);
3383 $c_max = $gs->rev_db_get($r_max);
3384 $c_min = $gs->rev_db_get($r_min);
3385 if (defined $c_min && defined $c_max) {
3386 if ($r_max > $r_max) {
3387 push @cmd, "$c_min..$c_max";
3388 } else {
3389 push @cmd, "$c_max..$c_min";
3390 }
3391 } elsif ($r_max > $r_min) {
3392 push @cmd, $c_max;
3393 } else {
3394 push @cmd, $c_min;
3395 }
3396 }
3397 return @cmd;
3398}
3399
3400# adapted from pager.c
3401sub config_pager {
3402 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3403 if (!defined $pager) {
3404 $pager = 'less';
3405 } elsif (length $pager == 0 || $pager eq 'cat') {
3406 $pager = undef;
3407 }
3408}
3409
3410sub run_pager {
3411 return unless -t *STDOUT;
3412 pipe my $rfd, my $wfd or return;
3413 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3414 if (!$pid) {
3415 open STDOUT, '>&', $wfd or
3416 ::fatal "Can't redirect to stdout: $!\n";
3417 return;
3418 }
3419 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3420 $ENV{LESS} ||= 'FRSX';
3421 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3422}
3423
21819a37
EW
3424sub tz_to_s_offset {
3425 my ($tz) = @_;
3426 $tz =~ s/(\d\d)$//;
3427 return ($1 * 60) + ($tz * 3600);
3428}
3429
f8c9d1d2
EW
3430sub get_author_info {
3431 my ($dest, $author, $t, $tz) = @_;
3432 $author =~ s/(?:^\s*|\s*$)//g;
3433 $dest->{a_raw} = $author;
3434 my $au;
1c8443b0 3435 if ($::_authors) {
f8c9d1d2
EW
3436 $au = $rusers{$author} || undef;
3437 }
3438 if (!$au) {
3439 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3440 }
3441 $dest->{t} = $t;
3442 $dest->{tz} = $tz;
3443 $dest->{a} = $au;
3444 # Date::Parse isn't in the standard Perl distro :(
3445 if ($tz =~ s/^\+//) {
21819a37 3446 $t += tz_to_s_offset($tz);
f8c9d1d2 3447 } elsif ($tz =~ s/^\-//) {
21819a37 3448 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
3449 }
3450 $dest->{t_utc} = $t;
3451}
3452
3453sub process_commit {
3454 my ($c, $r_min, $r_max, $defer) = @_;
3455 if (defined $r_min && defined $r_max) {
3456 if ($r_min == $c->{r} && $r_min == $r_max) {
3457 show_commit($c);
3458 return 0;
3459 }
3460 return 1 if $r_min == $r_max;
3461 if ($r_min < $r_max) {
3462 # we need to reverse the print order
3463 return 0 if (defined $limit && --$limit < 0);
3464 push @$defer, $c;
3465 return 1;
3466 }
3467 if ($r_min != $r_max) {
3468 return 1 if ($r_min < $c->{r});
3469 return 1 if ($r_max > $c->{r});
3470 }
3471 }
3472 return 0 if (defined $limit && --$limit < 0);
3473 show_commit($c);
3474 return 1;
3475}
3476
3477sub show_commit {
3478 my $c = shift;
3479 if ($oneline) {
3480 my $x = "\n";
3481 if (my $l = $c->{l}) {
3482 while ($l->[0] =~ /^\s*$/) { shift @$l }
3483 $x = $l->[0];
3484 }
3485 $l_fmt ||= 'A' . length($c->{r});
3486 print 'r',pack($l_fmt, $c->{r}),' | ';
3487 print "$c->{c} | " if $show_commit;
3488 print $x;
3489 } else {
3490 show_commit_normal($c);
3491 }
3492}
3493
3494sub show_commit_changed_paths {
3495 my ($c) = @_;
3496 return unless $c->{changed};
3497 print "Changed paths:\n", @{$c->{changed}};
3498}
3499
3500sub show_commit_normal {
3501 my ($c) = @_;
3502 print '-' x72, "\nr$c->{r} | ";
3503 print "$c->{c} | " if $show_commit;
3504 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3505 localtime($c->{t_utc})), ' | ';
3506 my $nr_line = 0;
3507
3508 if (my $l = $c->{l}) {
3509 while ($l->[$#$l] eq "\n" && $#$l > 0
3510 && $l->[($#$l - 1)] eq "\n") {
3511 pop @$l;
3512 }
3513 $nr_line = scalar @$l;
3514 if (!$nr_line) {
3515 print "1 line\n\n\n";
3516 } else {
3517 if ($nr_line == 1) {
3518 $nr_line = '1 line';
3519 } else {
3520 $nr_line .= ' lines';
3521 }
3522 print $nr_line, "\n";
3523 show_commit_changed_paths($c);
3524 print "\n";
3525 print $_ foreach @$l;
3526 }
3527 } else {
3528 print "1 line\n";
3529 show_commit_changed_paths($c);
3530 print "\n";
3531
3532 }
488a63ec 3533 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
3534 if ($c->{$x}) {
3535 print "\n";
3536 print $_ foreach @{$c->{$x}}
3537 }
3538 }
3539}
3540
3541sub cmd_show_log {
3542 my (@args) = @_;
3543 my ($r_min, $r_max);
3544 my $r_last = -1; # prevent dupes
3545 if (defined $TZ) {
3546 $ENV{TZ} = $TZ;
3547 } else {
3548 delete $ENV{TZ};
3549 }
3550 if (defined $::_revision) {
3551 if ($::_revision =~ /^(\d+):(\d+)$/) {
3552 ($r_min, $r_max) = ($1, $2);
3553 } elsif ($::_revision =~ /^\d+$/) {
3554 $r_min = $r_max = $::_revision;
3555 } else {
3556 ::fatal "-r$::_revision is not supported, use ",
3557 "standard \'git log\' arguments instead\n";
3558 }
3559 }
3560
3561 config_pager();
3bc718ba 3562 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
f8c9d1d2
EW
3563 my $log = command_output_pipe(@args);
3564 run_pager();
488a63ec 3565 my (@k, $c, $d, $stat);
f8c9d1d2
EW
3566 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3567 while (<$log>) {
3568 if (/^${esc_color}commit ($::sha1_short)/o) {
3569 my $cmt = $1;
3570 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3571 $r_last = $c->{r};
3572 process_commit($c, $r_min, $r_max, \@k) or
3573 goto out;
3574 }
3575 $d = undef;
3576 $c = { c => $cmt };
3577 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3578 get_author_info($c, $1, $2, $3);
3579 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3580 # ignore
3581 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3582 push @{$c->{raw}}, $_;
3583 } elsif (/^${esc_color}[ACRMDT]\t/) {
3584 # we could add $SVN->{svn_path} here, but that requires
3585 # remote access at the moment (repo_path_split)...
3586 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3587 push @{$c->{changed}}, $_;
3588 } elsif (/^${esc_color}diff /o) {
3589 $d = 1;
3590 push @{$c->{diff}}, $_;
3591 } elsif ($d) {
3592 push @{$c->{diff}}, $_;
488a63ec
EW
3593 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3594 $esc_color*[\+\-]*$esc_color$/x) {
3595 $stat = 1;
3596 push @{$c->{stat}}, $_;
3597 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3598 push @{$c->{stat}}, $_;
3599 $stat = undef;
f8c9d1d2
EW
3600 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3601 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);