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