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