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