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