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