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