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