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