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