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