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