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