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