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